简体   繁体   中英

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.

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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