--a table with id,name,createdate TestTable
--based on the name group, get the largest record (whole) of createdate in each group.
----------------------------------------------
Create a table with the following statement:
[SQL]View Plaincopyprint?
- CREATE TABLE [dbo].[ TestTable]
- (
- [ID] [int] not NULL IDENTITY (1, 1),
- [name] [nchar] (Ten) 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 test data:
[SQL]View Plaincopyprint?
- Insert into testtable (ID,name, counts,createdate) values(1, ' A ', *,' 10:52pm ')
- Insert into testtable (ID,name, counts,createdate) values (2,' A ', ten,' 10:52pm ')
- Insert into testtable (ID,name, counts,createdate) values(3, ' B ', +,' 10:52pm ')
- Insert into testtable (ID,name, counts,createdate) values (4,' B ', +,' 10:52pm ')
- Insert into testtable (ID,name, counts,createdate) values(5, ' B ', ten,' 10:52pm ')
- Insert into testtable (ID,name, counts,createdate) values (6,' C ',,' + 10:52pm ')
- Insert into testtable (ID,name, counts,createdate) values(7, ' C ', +-10:52pm ')
To query the SQL statement:
[SQL]View Plaincopyprint?
- 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
The results are as follows: