使用SQL如何编写查询以查找每个类别每月前5名?

时间:2017-12-21 05:19:39

标签: sql tsql

我试图在特定时间间隔(例如一个月)内获得每个类别中编号最高的前5行。我目前所拥有的返回5个类别的完全相同的描述。我想要进入前五名。这只有在我尝试根据时间段对其进行排序时才会发生。

WITH CustomerRank
AS
(SELECT 
    Count(*) AS "Count",
    d.Item,
    d.Description,
    Name,
    i.Type,
    d.CreatedOn    
FROM [dbo].i,
    d,
    dbo.b,
    as,
    a,
    c
WHERE d.Inspection_Id = i.Id  AND d.Inspection_Id = i.Id AND 
    b.Id = i.BuildingPart_Id AND b.as= Assessments.Id
    AND as.Application_Id = a.Id AND a.Customer_Id = Customers.Id                                
group by d.Item, d.Description, Name, i.Type, d.CreatedOn

)

select * from (
    SELECT "Count",Item,Description,Type,ROW_NUMBER()  Over (PARTITION BY Name order by "Count" desc) AS RowNum, Name, CreatedOn
    FROM CustomerRank  
where CreatedOn > '2017-1-1 00:00:00'

) s where RowNum <6 

干杯

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

as_json

我们的想法是必须从WITH CustomerRank AS (SELECT Count(*) AS "Count", d.Item, d.Description, Name, i.Type FROM dbo.Inspection i INNER JOIN dbo.Details d ON d.Inspection_Id = i.Id INNER JOIN dbo.BuildingParts b ON b.Id = i.BuildingPart_Id INNER JOIN dbo.Assessments a ON a.Id = b.AssessmentId INNER JOIN dbo.Applications ap ON ap.Id = a.Application_Id INNER JOIN dbo.Customers c ON c.Id = a.Customer_Id where CreatedOn > '2017-1-1 00:00:00' group by d.Item, d.Description, Name, i.Type ) select * from ( SELECT "Count",Item,Description,Type,ROW_NUMBER() Over (PARTITION BY Name order by "Count" desc) AS RowNum, Name FROM CustomerRank ) s where RowNum <6 子句中删除CreatedOn列(因为如果保留它,我们会为GROUP BY列的每个值获取不同的行)。

此外,最好为每个表使用JOIN-s和别名。