SQL,SUM + CASE

时间:2017-08-24 12:27:46

标签: sql sql-server sum case

我尝试这样做:

SELECT
  o.ID_DOSSIER,
  SUM(CASE WHEN ID_TYPE IN ('0','1') THEN SUM(TTL * -1) END) - SUM(CASE WHEN ID_TYPE IN ('2','3') THEN SUM(TTL) END)
FROM
  ope o,actor a
WHERE o.ID_ACTION=a.ID_ACTION
GROUP BY o.ID_DOSSIER

问我是否不知道我想做什么,

在喜欢

case 1 : ID_TYPE IN ('0','1') THEN TTL1 = TTL * -1
case 2 : ID_TYPE IN ('2','3') THEN TTL2 = TTL

TTL = TTL2 + TTL1

1 个答案:

答案 0 :(得分:3)

从不FROM子句中使用逗号。 始终使用正确的JOIN语法。

然后,您无法嵌套聚合函数,因此这应该足够了:

SELECT o.ID_DOSSIER,
       SUM(CASE WHEN ID_TYPE IN ('0', '1') THEN TTL * -1
                WHEN ID_TYPE IN ('2', '3') THEN TTL
           END)
FROM ope o JOIN
     actor a
     ON o.ID_ACTION = a.ID_ACTION
GROUP BY o.ID_DOSSIER