SQL 查询获取组的前 2 条记录
SQL Query to get top 2 records of group
我有以下输入Table
Source EventType
A X
A X
A X
A Y
A Y
A Z
B L
B L
B L
B L
B M
B N
B N
预期输出
Source EventType Frequency
A X 3
A Y 2
B L 4
B N 2
如何构造 SQL 查询以获得如上所示的结果?
我能够取得成果,但一次只有一个来源。
select TOP 2 eventype, count(*) as frequencey
from myEventTable
where source = 'A'
group by eventtype
order by count(*) desc
我们可以在这里使用ROW_NUMBER
:
WITH cte AS (
SELECT Source, EventType, COUNT(*) as Frequency,
ROW_NUMBER() OVER (PARTITION BY Source ORDER BY COUNT(*) DESC) rn
FROM myEventTable
GROUP BY Source, Eventtype
)
SELECT Source, EventType, Frequency
FROM cte
WHERE rn <= 2;
之所以有效,是因为 ROW_NUMBER
在 GROUP BY
操作完成后应用,即它针对组运行。然后我们可以很容易地限制每个来源的前 2 个,按照频率降序排列。
我有以下输入Table
Source EventType
A X
A X
A X
A Y
A Y
A Z
B L
B L
B L
B L
B M
B N
B N
预期输出
Source EventType Frequency
A X 3
A Y 2
B L 4
B N 2
如何构造 SQL 查询以获得如上所示的结果? 我能够取得成果,但一次只有一个来源。
select TOP 2 eventype, count(*) as frequencey
from myEventTable
where source = 'A'
group by eventtype
order by count(*) desc
我们可以在这里使用ROW_NUMBER
:
WITH cte AS (
SELECT Source, EventType, COUNT(*) as Frequency,
ROW_NUMBER() OVER (PARTITION BY Source ORDER BY COUNT(*) DESC) rn
FROM myEventTable
GROUP BY Source, Eventtype
)
SELECT Source, EventType, Frequency
FROM cte
WHERE rn <= 2;
之所以有效,是因为 ROW_NUMBER
在 GROUP BY
操作完成后应用,即它针对组运行。然后我们可以很容易地限制每个来源的前 2 个,按照频率降序排列。