zoukankan      html  css  js  c++  java
  • SQL 分组后获取其中一个字段最大值的整条记录

    ----------------------------------------------
    --有id,name,createDate的一张表testTable
    --根据name分组,获取每组中createDate最大的那条记录(整条)查询出来
    ----------------------------------------------

    创建一张表,语句如下:

    CREATE TABLE [dbo].[testTable]  

    (  

    [id] [int] NOT NULL IDENTITY(1, 1),  

    [name] [nchar] (10) COLLATE Chinese_PRC_CI_AS NULL,  

    [counts] [int] NULL,  

    [createDate] [datetime] NULL  

    )  

    GO  

    -- Constraints and Indexes  

    ALTER TABLE [dbo].[testTable] ADD CONSTRAINT [PK_testTable] PRIMARY KEY CLUSTERED ([id])  

    GO  

    插入测试数据:

    insert into testTable(id,name,counts,createDate) values(1,'A         ',20,'01 14 2011 10:52PM')  

    insert into testTable(id,name,counts,createDate) values(2,'A         ',10,'02 14 2011 10:52PM')  

    insert into testTable(id,name,counts,createDate) values(3,'B         ',20,'03 14 2011 10:52PM')  

    insert into testTable(id,name,counts,createDate) values(4,'B         ',40,'04 14 2011 10:52PM')  

    insert into testTable(id,name,counts,createDate) values(5,'B         ',10,'05 14 2011 10:52PM')  

    insert into testTable(id,name,counts,createDate) values(6,'C         ',20,'06 14 2011 10:52PM')  

    insert into testTable(id,name,counts,createDate) values(7,'C         ',40,'07 14 2011 10:52PM')  

     

     

    查询SQL语句:

     

    select * from (  

    select id,name,counts,createDate,row_number() over(partition by name order by createDate desc) rn  

    from testTable  

    ) t where t.rn <=1  

    结果如下:

  • 相关阅读:
    mac/unix系统:C++实现一个端口扫描器
    C++:通过gethostbyname函数,根据服务器的域名,获取服务器IP
    PostMan Setting Proxy 设置 代理
    企业架构 Red Hat Drools KIE Project 三大核心产品
    IDS,IPS,IPD
    Vehicle routing with Optaplanner graph-theory
    SonarQube Detection of Injection Flaws in Java, C#, PHP
    Spring AOP Log
    Code Quality and Security | SonarQube
    Gradle vs. Maven: Performance, Compatibility, Speed, & Builds
  • 原文地址:https://www.cnblogs.com/iomango/p/4221481.html
Copyright © 2011-2022 走看看