简体   繁体   English

如何在MSSQL中以SELECT记录为最新日期

[英]How to SELECT records for the latest date in MSSQL

From the below table i want to write a select statement where i can select the price of the items for the latest date.从下表我想写一个 select 声明,我可以 select 最新日期的项目价格。

Item  |  Price   | Date
------|----------|--------
1001  |   10      | 26-5-2019
1001  |   11      | 15-02-2020
1001  |   9       | 28-08-2020
1002  |   5       | 1/7/2019
1002  |   3       | 8/11/2019
1002  |   4       | 5/5/2020
1003  |   6       | 26-05-2019
1003  |   7       | 1/2/2020
1003  |   5       | 15-09-2020

Result should be as below:结果应如下所示:

Item  |  Price   | Date 
------|----------|-------- 
1001  |  9       | 28-08-2020 
1002  |  4       | 5/5/2020 
1003  |  5       | 15-09-2020 

Despite the fact that the table is unreadable and you haven't posted anything about what you have tried so far, I will try to help you...尽管该表不可读并且您到目前为止还没有发布任何关于您尝试过的内容,但我会尽力帮助您......

You can get the price via Window Functions - in this case row_number.您可以通过 Window 函数获取价格 - 在本例中为 row_number。 You should try something like the following:您应该尝试以下操作:

SELECT x.*
FROM (SELECT Item, Price, [Date], ROW_NUMBER() OVER (PARTITION BY Item ORDER BY [Date] DESC) AS rn) x
WHERE x.rn = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM