Groupby的多重条件

时间:2017-01-25 20:35:28

标签: sql sql-server

我的错误代码如下,“Msg 144,Level 15,State 1,Line 17 无法在GROUP BY子句列表中使用的表达式中使用聚合或子查询。 “

SELECT [sddoc],
  [Soldtopt],
  [tradingname],
  [DlvDate],
  SUM(try_cast(Netvalue AS FLOAT)) AS Netvalue,
  COUNT(DISTINCT SDDoc) AS Salesdoc ,
  COUNT(DISTINCT
  CASE
    WHEN Netvalue = '0'
    THEN 1
    ELSE NULL
  END) AS ZeroValue ,
  COUNT(DISTINCT SDDoc) - COUNT(DISTINCT
  CASE
    WHEN Netvalue = '0'
    THEN 1
    ELSE NULL
  END) AS Result
FROM d1
WHERE dlvdate='25.01.2017'
GROUP BY
  CASE
    WHEN SUM(try_cast(Netvalue AS FLOAT)) = 0
    AND COUNT(DISTINCT SDDoc)             = 1
    AND COUNT(DISTINCT
      CASE
        WHEN Netvalue = '0'
        THEN 1
        ELSE NULL
      END) = 1
    THEN [sddoc]
  END,
  Soldtopt,
  tradingname,
  DlvDate 

1 个答案:

答案 0 :(得分:1)

您不能在GROUP BY子句中使用SUM或COUNT(聚合)。必须在定义组后计算聚合值。

此外,您的CASE缺少ELSE子句。