如何定义 SQL 语句以获取 ID 的最后一行(SQL 服务器)
How to define a SQL statement to get the last row of an ID (SQL Server)
对于以下情况,我需要一个 sql 语句。在 table 中,我必须过滤 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 | ... |
....
怎么看唯一的IdentNo
可以有几个noID
。好吧,我需要一个 SQL 语句 return 就在 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 | ... |
....
目前我是这样处理的:
SELECT TOP 1 * FROM Test_Table_1 WHERE IdentNo = 991057 ORDER BY report_created DESC
但我必须对每个 IdentNo
进行自定义,仅此而已。
您可以使用 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
对于以下情况,我需要一个 sql 语句。在 table 中,我必须过滤 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 | ... |
....
怎么看唯一的IdentNo
可以有几个noID
。好吧,我需要一个 SQL 语句 return 就在 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 | ... |
....
目前我是这样处理的:
SELECT TOP 1 * FROM Test_Table_1 WHERE IdentNo = 991057 ORDER BY report_created DESC
但我必须对每个 IdentNo
进行自定义,仅此而已。
您可以使用 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