当有空值时,MYSQL组加总

时间:2016-11-04 03:03:13

标签: mysql

我正在尝试在mysql中执行组求和,但是空值导致问题。我使用了nullif / ifnull没有帮助

这是一个例子

 Group  Employee  Discipline  HardWork  Dedication
 101    DTF           1            1             1
 101    Tim             1             1            0
 101    Erk             NULL       1            0
 101    PMD           NULL       1            0
 101    NSE           1             1            0

SQL:

SELECT
    GROUP,
    SUM( EMPLOYEE ),
    SUM( DISCIPLINE ),
    SUM( HARDWORK ),
    SUM( DEDICATION )
FROM
    TABLE
GROUP BY
    GROUP,
    EMPLOYEE,
    DISCIPLINE,
    HARDWORK,
    DEDICATION

预期结果:

101---3----5----1

实际结果

101--5----5-----1

任何人都有任何想法?

2 个答案:

答案 0 :(得分:1)

尝试:

SUM(IFNULL( Discipline, 0 ))

而不是

SUM( DISCIPLINE )

第一个将取0的值是找到null。

答案 1 :(得分:0)

我认为你的查询应该是:

SELECT
    Group,
    COUNT( Employee ) AS EmployeeCountInGroup,
    SUM( ISNULL( Discipline, 0 ) ) AS SumDiscipline,
    SUM( ISNULL( HardWork, 0 ) ) AS SumHardWork,
    SUM( ISNULL( Dedication, 0 ) ) AS SumDedication
FROM
    TableName
GROUP BY
    Group