MySQL:获取表中每个组的第n个最高值

时间:2014-08-08 19:03:31

标签: mysql

免责声明:我对此非常陌生,所以如果我使用不正确的术语,我会提前道歉 - 我很乐意澄清是否有任何事情不清楚。

假设我有一个这样的表,它跟踪商店位置和部门的所有订单:

STORE          DEPT          ORDER          AMOUNT
--------------------------------------------------   
NYC            Clothing      P00001         $30
NYC            Clothing      P00002         $25
NYC            Clothing      P00003         $40
...            ...           ...            ...
NYC            Housewares    P00011         $140
NYC            Housewares    P00012         $125
NYC            Housewares    P00013         $140
...            ...           ...            ...
CHI            Clothing      P00021         $30
CHI            Clothing      P00022         $20
CHI            Clothing      P00023         $20
...            ...           ...            ...
CHI            Housewares    P00031         $180
CHI            Housewares    P00032         $110
CHI            Housewares    P00033         $125
...            ...           ...            ...

如果我想在每个商店中获得最高销量,我认为这只是

SELECT Store, Dept, max(Amount)
FROM mytable
GROUP BY Store, Dept

但是,如果我想要在每个部门中获得第二高的销量呢?换句话说,我想要一个查询,从上表中产生以下结果:

STORE          DEPT          ORDER          AMOUNT
--------------------------------------------------
NYC            Clothing      P00001         $30
NYC            Housewares    P00013         $140
CHI            Clothing      P00022         $20
CHI            Housewares    P00033         $125

请注意,我并不一定要获得第二高的独特金额 - 如果在最高价值方面达到平局,就像NYC-Housewares中那样,我需要返回的价值(不是125美元)。 / p>

在SQL Server中,我已经了解到我可以使用PARTITION BY在组内进行排序,然后选择我想要的排名,但它并不表示相同的语法适用于MySQL。我在网上发现的类似问题涉及使用LIMIT,但我还没有找到适合我情况的解决方案。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我希望有更好的方法,但你可以通过交叉或不连接两个子查询来获得这个:

Select mytable.Store, mytable.Dept, mytable.Order, mytable.Amount
from mytable m
inner join 
  (Select Amount from mytable n where m.store = n.store and m.dept = n.dept order by Amount desc limit 2) as high_enough
  on mytable.Amount = high_enough.Amount
left join 
   (Select Amount from mytable n where m.store = n.store and m.dept = n.dept order by Amount desc limit 2) as too_high
  where too_high.Amount is null
group by Store, Dept;