如何定义SQL语句以获取ID的最后一行(SQL Server)

yur*_*uro 0 sql sql-server greatest-n-per-group

对于以下情况,我需要一个sql语句.在表格中,我必须过滤Id的最后一个数据行.例如:

noID  | Name  | IdentNo | report_created | ... |
1     | testA | 991001  | 2013-01-02     | ... |
1     | testA | 991001  | 2015-06-20     | ... | //this is the last of noID=1
3     | testB | 991002  | 2014-01-23     | ... |
4     | testC | 991003  | 2012-05-02     | ... |
4     | testC | 991003  | 2014-07-30     | ... |
4     | testC | 991003  | 2015-10-11     | ... | //this is the last of noID=4
120   | testC | 991003  | 2016-03-02     | ... |
....
Run Code Online (Sandbox Code Playgroud)

你怎么看独特的IdentNo可以有几个noID.好吧,我需要一个SQL语句来返回最后一行noID.

这将是sql语句的结果:

noID  | Name  | IdentNo | report_created | ... |
1     | testA | 991001  | 2015-06-20     | ... |
3     | testB | 991002  | 2014-01-23     | ... |
4     | testC | 991003  | 2015-10-11     | ... |
120   | testC | 991003  | 2016-03-02     | ... |
....
Run Code Online (Sandbox Code Playgroud)

目前我处理如下:

SELECT TOP 1 * FROM Test_Table_1 WHERE IdentNo = 991057 ORDER BY report_created DESC
Run Code Online (Sandbox Code Playgroud)

但我必须自定义每一个IdentNo和那个.

cab*_*oad 7

您可以使用sql server partition by子句,然后按report_created desc排序,然后获取第一行.

select a.* from 
(select noId,Name,IdentNo,report_created,
row_number over (partition by noId order by report_created desc) as rnum
from your table)a
where a.rnum=1
Run Code Online (Sandbox Code Playgroud)