我在MS SQL中有一个数据库表
Date Make Model Price
4-Apr-17 Toyota Avalon 34000
5-Apr-17 Merc ML350 45000
6-Apr-17 BMW 5X 55000
7-Apr-17 Totoya Camry 28000
8-Apr-17 Merc ML350 46000
9-Apr-17 BMW 5X 54000
10-Apr-17 Totoya Camry 25000
11-Apr-17 Merc ML350 47000
12-Apr-17 Toyota Avalon 36000
13-Apr-17 BMW 5X 53000
14-Apr-17 Toyota Avalon 35500
15-Apr-17 BMW 5X 53500
16-Apr-17 Toyota Avalon 35500
17-Apr-17 Merc ML350 46500
我想得到每种型号的最新价格。因此我的输出应该是
Date Make Model Price
10-Apr-17 Totoya Camry 25000
15-Apr-17 BMW 5X 53500
16-Apr-17 Toyota Avalon 35500
17-Apr-17 Merc ML350 46500
答案 0 :(得分:2)
您应该使用ROW_NUMBER
:
WITH CTE AS
(
SELECT *,
RN = ROW_NUMBER() OVER(PARTITION BY Make, Model
ORDER BY [Date] DESC)
FROM dbo.YourTable
)
SELECT *
FROM CTE
WHERE RN = 1;
答案 1 :(得分:1)
一种方法是将窗口函数row_number
与top 1 with ties
:
select top 1 with ties *
from your_table
order by row_number() over (
partition by make, model
order by [date] desc
);
这样可以避免子查询/ CTE。