我的表格如下所示:
+---------+---------+----------+
|id |title |date |
+---------+---------+----------+
|1 |A |2017-05-01|
|2 |C |2017-05-01|
|3 |A |2017-05-02|
|4 |A |2017-05-01|
|5 |A |2017-05-03|
|6 |B |2017-05-01|
|7 |A |2017-05-01|
|8 |D |2017-05-03|
|9 |A |2017-05-02|
|10 |B |2017-05-01|
|11 |A |2017-05-01|
|12 |C |2017-05-02|
|13 |A |2017-05-01|
|14 |B |2017-05-01|
|15 |B |2017-05-04|
|16 |A |2017-05-03|
|17 |B |2017-05-01|
|18 |A |2017-05-01|
+---------+---------+----------+
我想查询此表并按日期返回计数(前2名)。所以,我希望它返回以下内容:
+---------+---------+----------+
|count |title |date |
+---------+---------+----------+
|6 |A |2017-05-01|
|4 |A |2017-05-02|
|1 |A |2017-05-03|
|4 |B |2017-05-01|
|5 |B |2017-05-02|
|6 |B |2017-05-03|
+---------+---------+----------+
(结果可能与我在样本表中的内容不符),但我认为重点可能就在那里。
答案 0 :(得分:0)
我认为您的问题需要两个聚合,第一个用于查找每个标题/日期组合的计数,第二个用于保留每个日期的两个最大计数。
WITH cte1 AS (
SELECT title, date, COUNT(*) AS t_count
FROM yourTable
GROUP BY title, date
),
cte2 AS (
SELECT title, date, t_count,
ROW_NUMBER() OVER (PARTITION BY date ORDER BY t_count DESC) rn
FROM cte1
)
SELECT title, date, t_count
FROM cte2
WHERE rn <= 2
答案 1 :(得分:0)
您可以单步结合窗口函数和聚合函数:
select cnt, title, date
from (select t.date, t.title, count(*) as cnt,
row_number() over (partition by date order by count(*) desc) as seqnum
from t
group by t.date, t.title
) t
where seqnum <= 2;