使用带有COUNT的CASE中的列而不将其放在group by中

时间:2017-08-11 20:30:23

标签: sql sql-server-2014

SELECT 
    COUNT([P].[pkPortfolioId]) AS [OutcomeNotSubmitted],
    [CG].[GroupName]
FROM
    opp.Portfolio AS [P]
INNER JOIN 
   [vendor].[CustomerGroup] AS [CG] ON [P].[fkCustomerGroupId] = [CG].[pkCustomerGroupId]
WHERE 
    fkOutcomeId IS NULL
GROUP BY 
    [CG].[GroupName]

此查询工作正常但有多种结果如下所示。为了使此查询起作用,我需要复制此查询以获得所需的结果。此外还有很多连接。请记住这是修剪后的查询。

我想达到这个结果:

NAME    WIN    PartialWin    Loss    OutcomeNotSubmitted
---------------------------------------------------------
Chain    1        0           1                 0

下面是我尝试在一个查询中实现此目的

SELECT 
    CASE
        WHEN [P].[fkOutcomeId] = 1 THEN COUNT([P].[pkPortfolioId])
    END AS [Win],
    CASE
        WHEN [P].[fkOutcomeId] = 2 THEN COUNT([P].[pkPortfolioId])
    END AS [PartialWin],
    CASE
        WHEN [P].[fkOutcomeId] = 3 THEN COUNT([P].[pkPortfolioId])
    END AS [Loss],
    CASE
        WHEN [P].[fkOutcomeId] IS NULL THEN COUNT([P].[pkPortfolioId])
    END AS [OutcomeNotSubmitted],
    [CG].[GroupName]
FROM 
    opp.Portfolio AS [P]
INNER JOIN 
    [vendor].[CustomerGroup] AS [CG] ON [P].[fkCustomerGroupId] = [CG].[pkCustomerGroupId]
GROUP BY 
    [CG].[GroupName]

错误:

  

专栏' opp.Portfolio.fkOutcomeId'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

1 个答案:

答案 0 :(得分:3)

订单错误。 case应该是聚合函数的参数。假设投资组合ID从不NULL,我会使用SUM()

SELECT SUM(CASE WHEN [P].[fkOutcomeId] = 1 THEN 1 ELSE 0 END) AS Win,
       SUM(CASE WHEN [P].[fkOutcomeId] = 2 THEN 1 ELSE 0 END) AS PartialWin,
       SUM(CASE WHEN [P].[fkOutcomeId] = 3 THEN 1 ELSE 0 END) AS Loss,
       SUM(CASE WHEN [P].[fkOutcomeId] IS NULL THEN 1 ELSE 0 END) AS OutcomeNotSubmitted,
       [CG].[GroupName]
FROM opp.Portfolio [P] INNER JOIN
     [vendor].[CustomerGroup] [CG]
     ON [P].[fkCustomerGroupId] = [CG].[pkCustomerGroupId]
GROUP BY [CG].[GroupName];