我有一个如下所示的选择:
SELECT
ReportingDate
, PortfolioID
, PortfolioNme
, CASE
WHEN @ReportType = 'GeoCountry' THEN Infoportal.dbo.fn_Generic_ProperCase(Country)
WHEN @ReportType = 'GeoEquity' THEN Region
END AS Country
, RANK() OVER (PARTITION BY PortfolioID ORDER BY SUM(Percentage) DESC, CASE WHEN @ReportType = 'GeoCountry' THEN Country WHEN @ReportType = 'GeoEquity' THEN Region END) AS [Rank]
, SUM(Percentage) AS [Weight]
FROM @Worktable as WT
WHERE WT.IssueType1 <> '010' AND WT.IssueType2 <> '055'
GROUP BY WT.ReportingDate
, WT.PortfolioID
, WT.PortfolioNme
, CASE
WHEN @ReportType = 'GeoCountry' THEN WT.Country
WHEN @ReportType = 'GeoEquity' THEN WT.Region
END
我要做的是按国家或地区分组,具体取决于@ReportType,并显示百分比和排名的总和。
但是我一直收到错误:
Msg 8120,Level 16,State 1,Line 349
列'@ Worktable.Country'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
Msg 8120,Level 16,State 1,Line 350
列'@ Worktable.Region'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
这很容易,真让我讨厌。非常感谢帮助。
由于
答案 0 :(得分:8)
我相信CTE会简化你想要做的事情:
;WITH WT AS (
SELECT
ReportingDate
, PortfolioID
, PortfolioNme
, CASE
WHEN @ReportType = 'GeoCountry'
THEN Infoportal.dbo.fn_Generic_ProperCase(Country)
WHEN @ReportType = 'GeoEquity'
THEN Region
END AS Country
, Percentage
FROM @Worktable
WHERE IssueType1 <> '010' AND IssueType2 <> '055'
)
SELECT
ReportingDate
, PortfolioID
, PortfolioNme
, Country
, RANK() OVER (
PARTITION BY PortfolioID
ORDER BY SUM(Percentage) DESC, Country) AS [Rank]
, SUM(Percentage) AS [Weight]
FROM WT
GROUP BY
ReportingDate
, PortfolioID
, PortfolioNme
, Country
答案 1 :(得分:0)
select ReportingDate, PortfolioID, PortfolioNme, Country, RANK() OVER (PARTITION BY PortfolioID ORDER BY SUM(Percentage) DESC, CountryOrRegion) AS [Rank], SUM(Percentage) AS [Weight]
from (
SELECT
ReportingDate
, PortfolioID
, PortfolioNme
, CASE WHEN @ReportType = 'GeoCountry' THEN Country WHEN @ReportType = 'GeoEquity' THEN Region END as CountryOrRegion
, CASE
WHEN @ReportType = 'GeoCountry' THEN Infoportal.dbo.fn_Generic_ProperCase(Country)
WHEN @ReportType = 'GeoEquity' THEN Region
END AS Country
FROM @Worktable as WT
WHERE WT.IssueType1 <> '010' AND WT.IssueType2 <> '055'
) t
GROUP BY WT.ReportingDate
, WT.PortfolioID
, WT.PortfolioNme
, CountryOrRegion