4

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

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 按国家或地区分组,并显示百分比和排名的总和。

但是我不断收到错误消息:

消息 8120,级别 16,状态 1,第 349
行列“@Worktable.Country”在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。
消息 8120,级别 16,状态 1,行 350
列“@Worktable.Region”在选择列表中无效,因为它既不包含在聚合函数或 GROUP BY 子句中。

这太容易了,真的让我很烦。帮助将不胜感激。

谢谢

4

2 回答 2

9

我相信 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
于 2013-03-01T16:28:06.460 回答
1
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    
于 2013-03-01T16:29:35.703 回答