SQL - 将NULL值更改为0

时间:2015-06-02 09:20:12

标签: sql null pivot

我有这个数据透视表,它为SUM(contar)提供了空值,我想将它们更改为0

SELECT Description AS Categoria,
       [ACS],
       [URO]
FROM
  (SELECT GroupType.Description,
          Speciality.Shortname,
          SUM(1) AS contar
   FROM DoctorEnterpriseDetails
   INNER JOIN Speciality ON DoctorEnterpriseDetails.Speciality1 = Speciality.SpecialityId
   INNER JOIN GroupType ON DoctorEnterpriseDetails.GroupId = GroupType.GroupId
   WHERE (DoctorEnterpriseDetails.EnterpriseId = 48)
   GROUP BY GroupType.Description,
            Speciality.Shortname) AS ps PIVOT (SUM(contar)
                                               FOR Shortname IN ([ACS],[URO])) pvt
ORDER BY description

我试过这样做,但它再次给了我Null值

SELECT Description AS Categoria,
       [ACS],
       [URO]
FROM
  (SELECT GroupType.Description,
          Speciality.Shortname,
          GroupType.GroupId,
          (CASE WHEN (SUM(1) IS NULL) THEN 0 ELSE SUM(1) END) AS contar
   FROM DoctorEnterpriseDetails
   INNER JOIN Speciality ON DoctorEnterpriseDetails.Speciality1 = Speciality.SpecialityId
   INNER JOIN GroupType ON DoctorEnterpriseDetails.GroupId = GroupType.GroupId
   WHERE (DoctorEnterpriseDetails.EnterpriseId = 48)
   GROUP BY GroupType.Description,
            Speciality.Shortname,
            DoctorEnterpriseDetails.GroupId,
            GroupType.GroupId) AS ps PIVOT (SUM(contar)
                                            FOR Shortname IN ([ACS],[URO])) pvt
ORDER BY GroupId;

我不明白出了什么问题。谢谢

1 个答案:

答案 0 :(得分:2)

您在CASE中定义别名,这是不允许的。另外你混合数字和字符串:

要么是

CASE WHEN SUM(1) IS NULL THEN 0 ELSE SUM(1) END AS contador

COALESCE(SUM(1), 0) END AS contador

顺便说一下,SUM(1)COUNT(*)

相同