每组最大n;领带的多种处理方式?

时间:2018-07-20 08:31:05

标签: sql tsql greatest-n-per-group

通常我必须在组中找到一个MAX / MIN值。解决此问题的方法有很多,但是他们似乎没有考虑的一件事就是处理领带。

例如,获取具有以下记录的数据集:

category   | product      | profit 2018  | profit 2017 | descr    
-------------------------------------------------------------
bicycles   | mountainbike | 10000        | 10000       |  ~~~~ 
bicycles   | blue bicycle | 12000        | 12000       |  ~~~~
bicycles   | unicycle     |  6500        |  7000       |  ~~~~
bicycles   | red bicycle  | 12000        | 14000       |  ~~~~
accessories| light        |  5000        |  3500       |  ~~~~
accessories| water bottle |  3200        |  2500       |  ~~~~
parts      | wheel        |  4000        |  4000       |  ~~~~
parts      | saddle       |  4000        |  3000       |  ~~~~

如果我想在2018年每个类别(solved here)上找到最有利可图的产品,则每个类别将获得多行,因为蓝色和红色的自行车绑在一起,车轮和鞍座也绑在一起。说我只想要一个结果(无论出于何种原因)。

我知道两种处理方法:

  1. 使用ROW_NUMBER()OVER(PARTITION BY ... ORDER BY ...)并将查询包装在CTE中,然后选择WHERE ROW_NUMBER = 1。 这种解决方案的优点是,我可以按顺序使用决胜局,例如,我可以将Profit 2017作为决胜局

  2. 选择前1名。此解决方案仅给出随机结果?

在这种情况下,有没有更好的方式处理关系?

1 个答案:

答案 0 :(得分:1)

首先,您的表中有一些identity列。然后,您可以将逻辑简化为:

select t.*
from table t
where identity_field = (select top (1) t1.identity_field 
                        from table t1
                        where t1.category = t.category
                        order by t1.profit_2018 desc
                       );