使用SQL返回每个组中计数的前3个值

时间:2016-02-06 22:45:52

标签: sql

我需要一个查询来返回每个组中计数的前3个值 - 我可以这样做吗?

所以,如果我目前使用(制作示例)

SELECT Client, Colour, COUNT(*)
FROM tblOrders
GROUP BY Client, Colour
ORDER BY Client, Colour, COUNT(*) DESC

获取

Client A|Green|275
Client A|Red|189
Client A|Blue|154
Client A|Purple|133
Client A|Black|14
Client B|Red|1025
Client B|Yellow|888
Client B|Blue|684
Client B|Brown|89

但我只想要

Client A|Green|275
Client A|Red|189
Client A|Blue|154
Client B|Red|1025
Client B|Yellow|888
Client B|Blue|684

1 个答案:

答案 0 :(得分:0)

您可以使用ANSI标准ROW_NUMBER()函数执行此操作:

SELECT Client, Colour, cnt
FROM (SELECT Client, Colour, COUNT(*) as cnt,
             ROW_NUMBER() OVER (PARTITION BY Client ORDER BY COUNT(*) DESC) as seqnum
      FROM tblOrders o
      GROUP BY Client, Colour
     ) cc
WHERE seqnum <= 3
ORDER BY Client, Colour, cnt DESC;