带有条件的SQL和

时间:2017-03-13 09:08:29

标签: sql sql-server select sum

我有一个需要总结值的查询,但在我的表格列中,有一个增量和减量值。
对于递减值,即使它在表中存储为正值,它的值也必须为负值。
虽然增加值,但仍保持正值。

我的查询如下:

SELECT
    SUM(
        CASE WHEN ACTIVITY_TYPE = '0' THEN -(ACTIVITY_VALUE)
        ELSE ACTIVITY_VALUE
        END
        ) AS NEW_ACTIVITY_VALUE
FROM V_EMPLOYEE_PAYACT
WHERE ACTIVITY_TYPE IN ('0','1') 
    AND EMPLOYEE_NO = '00002789' 
    AND ((YEAR = 2014 AND MONTH <= 4)
        OR
        (YEAR > 2013 AND YEAR <2014)
        OR
        (YEAR = 2013 AND MONTH >= 5)) 
GROUP BY YEAR, MONTH

它返回这个结果:
NEW_ACTIVITY_VALUE
391.00
-600.00

我需要将值设为-209(这两个数字的总和)

2 个答案:

答案 0 :(得分:1)

您目前正在按月和年的唯一组合对总和进行分组。如果你想要总和,只需删除group by子句:

SELECT
    SUM(
        CASE WHEN ACTIVITY_TYPE = '0' THEN -(ACTIVITY_VALUE)
        ELSE ACTIVITY_VALUE
        END
        ) AS NEW_ACTIVITY_VALUE
FROM V_EMPLOYEE_PAYACT
WHERE ACTIVITY_TYPE IN ('0','1') 
    AND EMPLOYEE_NO = '00002789' 
    AND ((YEAR = 2014 AND MONTH <= 4)
        OR
        (YEAR > 2013 AND YEAR <2014)
        OR
        (YEAR = 2013 AND MONTH >= 5)) 

答案 1 :(得分:1)

试试这个:

SELECT
    SUM(
        CASE
        WHEN ACTIVITY_TYPE = '0' THEN
            - (ACTIVITY_VALUE)
        ELSE
            ACTIVITY_VALUE
        END
    ) AS NEW_ACTIVITY_VALUE
FROM
    V_EMPLOYEE_PAYACT
WHERE
    ACTIVITY_TYPE IN ('0', '1')
AND EMPLOYEE_NO = '00002789'
AND (
    (YEAR = 2014 AND MONTH <= 4)
    OR (YEAR > 2013 AND YEAR < 2014)
    OR (YEAR = 2013 AND MONTH >= 5)
)