为一组列获取一列(价格)的最大值(日期)(make.model)

时间:2017-05-12 17:44:10

标签: sql-server join max row-number

我在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

2 个答案:

答案 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_numbertop 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。