我有以下最终选择声明:
SELECT ReportingDate
,PortfolioID
,IssueNme
,ROW_NUMBER() OVER (PARTITION BY PortfolioID ORDER BY SUM(Percentage) DESC) AS [Rank]
,CAST(SUM(Percentage) AS DECIMAL(22,1)) AS [Weight]
FROM @Worktable as WT
WHERE WT.IssueType1 IN ('020')
GROUP BY WT.ReportingDate, WT.PortfolioID, WT.IssueNme
ORDER BY [Weight] DESC
但是我希望看到每个portfolioID只排名前10位。我如何确保获得分组的每个PortfolioID的前10名?
答案 0 :(得分:1)
您可以使用CTE
。我会改用RANK
,但每组你可能会得到10以上。
WITH CTE AS
(
SELECT
RANK() OVER (PARTITION BY PortfolioID ORDER BY SUM(Percentage) DESC) AS [RANK]
, ReportingDate
, PortfolioID
, IssueNme
, CAST(SUM(Percentage) AS DECIMAL(22,1)) AS [Weight]
FROM @Worktable as WT
WHERE WT.IssueType1 IN ('020')
GROUP BY WT.ReportingDate, WT.PortfolioID, WT.IssueNme
)
SELECT
ReportingDate
, PortfolioID
, IssueNme
, [Weight]
FROM CTE
WHERE [RANK] <= 10
ORDER BY [Weight] DESC