聚合函数中的子查询

时间:2018-03-29 04:37:48

标签: sql sql-server

示例:

实际上是一个重复的查询

    Select Style_Color, Style_Color_Desc, RPT, Weeks, 
      Minimum, 
Max(CASE WHEN Cluster_ID in ('0150') then CAST(c.APS_Dev as decimal(10, 2)) end) AS 'APS Dev'
Max(CASE WHEN Cluster_ID in ('0082') then CAST(c.APS_Dev as decimal(10, 2)) end) AS 'APS Dev'
Max(CASE WHEN Cluster_ID in ('0096') then CAST(c.APS_Dev as decimal(10, 2)) end) AS 'APS Dev'
   From Cluster_Data 
     group by Style_Color, Style_Color_Desc,RPT, Weeks, Minimum
          Order by rpt, Style_Color

我想用聚合函数

中的子查询替换代码
  Select Style_Color, Style_Color_Desc, RPT, Weeks, 
      Minimum, 
Max(CASE WHEN Cluster_ID in (Select Cluster_ID From Cluster_Data2) then CAST(c.APS_Dev as decimal(10, 2)) end) as 'APS Dev'

   From Cluster_Data 
     group by Style_Color, Style_Color_Desc, RPT, Weeks, Minimum
          Order by rpt, Style_Color

获取错误

  

"无法对包含的表达式执行聚合函数   聚合或子查询"

1 个答案:

答案 0 :(得分:0)

您可以在子查询中进行计算:

select  ... 
,       max(CASE WHEN IsInData = 1 THEN CAST(c.APS_Dev as decimal(10, 2)) END) as 'APS Dev'
from    (
        select  *
        ,       case when Cluster_ID in (Select Cluster_ID From Cluster_Data) then 1 end
                    as IsInData
        from    Cluster_Data
        ) sub
group by
        ...

请注意,Cluster_ID中的Cluster_Data始终位于Cluster_Data,因此您的情况始终为真。