gpt4 book ai didi

sql-server - 带 CASE 的 GROUP BY - sql

转载 作者:行者123 更新时间:2023-12-03 01:55:57 24 4
gpt4 key购买 nike

我有一个如下所示的选择:

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
Column '@Worktable.Country' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Msg 8120, Level 16, State 1, Line 350
Column '@Worktable.Region' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

这太简单了,但我真的很烦。我们将不胜感激。

谢谢

最佳答案

我相信 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

关于sql-server - 带 CASE 的 GROUP BY - sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15162162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com