从所有总计中获取不同的值

时间:2015-09-04 09:26:15

标签: sql sql-server query-optimization

我有这个表结构:

TenancyUser

我想要明确,只有销量最高的车辆 所以只有这样:

Make    Model   Year    Sales
Toyota  Corolla 2014    15
Toyota  CAMRY   2014    12
Toyota  Camry   2015    7
Toyota  COROLLA 2015    5
Toyota  RAV4    2014    4
Toyota  RAV4    2015    2

1 个答案:

答案 0 :(得分:0)

row_numberMake以及Model销售额按降序排列order by分区。
然后选择rn = 1

的行
;with cte as
(
    select rn=row_number() over
    (
        partition by Make,Model
        order by sales desc
    ),*
    from sales
) 
select Make,Model,[Year],Sales 
from cte
where rn = 1
order by Sales desc;

Fiddle demo