sum case 问题,groupby 子句没有列

Posted

技术标签:

【中文标题】sum case 问题,groupby 子句没有列【英文标题】:sum case issue , no column for groupby clause 【发布时间】:2020-03-12 10:19:05 【问题描述】:

我有疑问:

SELECT leads,
       touched,
       invalid,
       TQL,
       SQOs,
       Wins,
       (touched / (CONVERT(decimal(7, 2), leads)) * 100) AS [touch%],
       (t.invalid / touched) AS [Invalid Leads%],
       (TQL / (CONVERT(decimal(7, 2), touched)) * 100) AS [TQL %],
       (SQOs / (CONVERT(decimal(7, 2), TQL)) * 100) AS [SQO%],
       (Wins / (CONVERT(decimal(7, 2), TQL)) * 100) AS [Wins%]
FROM (SELECT COUNT([lead id]) AS leads,
             SUM(CASE
                      WHEN a.status = 'Disqualified'
                        OR a.status = 'Qualified'
                       AND a.[Status Reason] <> 'Expired' THEN 1
                      ELSE 0
                 END) AS touched,
             SUM(CASE
                      WHEN a.status = 'Disqualififed'
                       AND a.[Status Reason] IN ('Already Engaged', 'Already purchased', 'Invalid Contact Info', 'Misrouted Lead', 'Non-Supported Market', 'Partner') THEN 1
                      ELSE 0
                 END) AS invalid,
             SUM(CASE WHEN a.status = 'Qualified' THEN 1 ELSE 0 END) AS TQL,
             SUM(CASE WHEN b.status = 'Open' THEN 1 ELSE 0 END) AS SQOs,
             SUM(CASE WHEN b.status = 'Won' THEN 1 ELSE 0 END) AS Wins,
             CASE WHEN b.status = 'Won' THEN SUM([End Cust Purchase Amount Const $])END AS tqlrevenue
      FROM lead a
           LEFT JOIN opportunity b ON a.[Opportunity Id (Qualifying Opportunity) (Opportunity)] = b.[Opportunity Id]
           LEFT JOIN MSSalesMalaysia_Updated c ON b.[Opportunity Id] = c.[opp id]
      WHERE a.[Lead Source] = 'Marketing') t;

当我添加表达式 case when B.status ='Won' then sum([End Cust Purchase Amount Const $]) end as tqlrevenue 时,我收到以下错误:

选择列表中的列 'opportunity.Status' 无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。

现在子查询中的所有列都是case条件,要包括哪一列?

【问题讨论】:

应该CASE 不应该在SUM 之内,而不是在它之外,就像您拥有的所有其他表达式一样? IE。 SUM(CASE WHEN a.status = 'Qualified' THEN 1 ELSE 0 END) AS TQL。这似乎是一个印刷错误。 CASE WHEN b.status = 'Won' THEN SUM([End Cust Purchase Amount Const $])END AS tqlrevenue 应该在分组中 另一种说法:Bad habits to kick : using table aliases like (a, b, c) or (t1, t2, t3) @DigvijayS 聚合函数不能出现在GROUP BY 子句中。 【参考方案1】:

您可能需要条件聚合:

sum(case when B.status ='Won' then [End Cust Purchase Amount Const $]) end) as tqlrevenue

也就是说,case 表达式是 sum() 的参数。

【讨论】:

以上是关于sum case 问题,groupby 子句没有列的主要内容,如果未能解决你的问题,请参考以下文章

SUM 值按列分组,但不能“聚合”?

7.03 对某列的值求和

SQL Group By 子句详解

SQL Server报错:选择列表中的列无效,因为该列没有包含在聚合函数或 GROUP BY 子句中

为啥select 子句中的字段一定要出现在Groupby子句中

在 sum case 中使用 exists 子句(oracle)