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  

 

結果如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM