如何使用公用表表达式用于SQL Server的多个列

时间:2015-12-03 07:26:08

标签: sql-server query-optimization common-table-expression

我的查询为:

WITH CTE
AS
(
SELECT AIP.aid [Author_ID], CAST(P.research_area as VARCHAR(100)) [Research_Area], 
       P.research_area_category_id [Category], COUNT(*) [Paper_Count], 
       P.p_year [Paper_Year]
FROM author_individual_papers AIP
JOIN sub_aminer_paper P ON AIP.pid = P.pid
WHERE AIP.aid IN (SELECT aid FROM Authors) AND P.p_year = 2005
GROUP BY AIP.aid, CAST(P.research_area as VARCHAR(100)),
         P.research_area_category_id, P.p_year
),
CTE1 AS
(SELECT *, ROW_NUMBER() OVER(PARTITION BY Author_ID ORDER BY Paper_Count DESC) AS Rank
 FROM CTE
)
SELECT * 
FROM CTE1
WHERE Rank <= 3  

这样输出为:

Author_ID   Research_Area   Category    Paper_Count Paper_Year  Rank
677         probabilistic   12          1           2005        1
677         feature extract 8           1           2005        2
677         image annotate  11          1           2005        3
1359        image represent 11          2           2005        1
1359        kernel method   14          1           2005        2
1359        data grid       8           1           2005        3
6242        info system     12          1           2005        1
6242        capable model   21          1           2005        2
6242        clustering      8           1           2005        3
8318        power manage    17          1           2005        1
...  
...  

现在我希望所有这些输出多年,即P.p_year介于20052014之间。但是,如果我使用P.p_year BETWEEN 2005 AND 2014,那么它会将输出与Paper_Count整数十年混合然后对它们进行排名,而我需要为每个P.p_year和每个{{1}分别排名}

0 个答案:

没有答案