我使用SSIS包每天更新我的内容。有数千个内容具有不同的审核ID,我想计算每个审核ID的前十个类别。在我意识到我应该为每个ModerationId计算它之前,我使用此查询来获取要更新的内容:
SELECT TOP 10 ModerationId, Category, COUNT(ContentSeqNum) AS Total FROM Content
WHERE Category IS NOT NULL
GROUP BY ModerationId, Category ORDER BY ModerationId, Total DESC
这是一种错误的方法,因为此查询计算所有数据的前十个类别,对于不同的ModerationId,它应该是不同的前十个类别。
如何更改此查询以计算每个ModerationId的前10个类别?
答案 0 :(得分:2)
使用Window Function
来计算categories
的前十名Moderation ID
。试试这个。
SELECT moderationid,
category,
total
FROM (SELECT Row_number() OVER (partition BY moderationid
ORDER BY Count(contentseqnum)) Rn,
moderationid,
category,
Count(contentseqnum) AS Total
FROM content
WHERE category IS NOT NULL
GROUP BY moderationid,
category) A
WHERE rn <= 10
答案 1 :(得分:1)
试试这个:
SELECT TOP(10) ModerationId, Category, COUNT(ContentSeqNum) OVER(PARTITION BY ModerationId ORDER BY ModerationId) AS Total
FROM Content
WHERE Category IS NOT NULL
ORDER BY Total DESC
答案 2 :(得分:1)
使用Row_number()函数
select * from
(
select *,
row_number() over(partition by ModerationId order by ModerationId) as sno
from Content WHERE Category IS NOT NULL
) as t
where sno<=10
在http://beyondrelational.com/modules/2/blogs/70/posts/10845/return-top-n-rows.aspx
查找更多方法