我知道这对你们大多数人来说很简单!
我有一个像这样的发票表:
+-----------+------------+------+-------+
| InvoiceID | Date | Item | Price |
+-----------+------------+------+-------+
| 1 | 15/04/2014 | A | 12 |
| 2 | 20/04/2014 | A | 20 |
| 3 | 20/04/2014 | A | 27 |
| 4 | 20/04/2014 | B | 29 |
| 5 | 28/04/2014 | C | 16 |
| 6 | 28/04/2014 | B | 11 |
+-----------+------------+------+-------+
我想根据每件商品的最后发票ID检索价格,所以:
+------+-----------+
| Item | LastPrice |
+------+-----------+
| A | 27 |
| B | 11 |
| C | 16 |
+------+-----------+
最有效的方法是什么?我使用的是SQL Server 2008
非常感谢任何收到的帮助。
答案 0 :(得分:4)
with cte as (
select *, row_number() over (partition by Item order by date desc) as r
from dbo.YourTable
)
select * from cte where r = 1
答案 1 :(得分:0)
这可以做你的工作:
SELECT Item,
Price AS 'LastPrice'
FROM MyTable
WHERE InvoiceId IN (SELECT Max(InvoiceId)
FROM MyTable
GROUP BY Item)