按行计数零行不显示

时间:2017-02-05 21:26:45

标签: sql

我想计算每componistId行的行数。当我运行以下SQL语句时,它可以正常工作:

SELECT C.componistId, COUNT(*)
FROM Componist C LEFT JOIN Stuk S ON S.componistId = C.componistId
GROUP BY C.componistId

现在我只想要stukNrOrigineel为空的行

SELECT C.componistId, COUNT(*)
FROM Componist C LEFT JOIN Stuk S ON S.componistId = C.componistId
WHERE S.stuknrOrigineel IS NULL
GROUP BY C.componistId

但是当我这样做时,结果为0的所有行都会消失。仅显示至少包含1行的行。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

您需要在on子句中包含条件:

SELECT C.componistId, COUNT(C.componistId)
FROM Componist C LEFT JOIN
     Stuk S
     ON S.componistId = C.componistId AND
        S.stuknrOrigineel IS NULL
GROUP BY C.componistId;

注意:我将COUNT()更改为第二个表中的计数。这通常是LEFT JOINCOUNT()合并时的所需内容。

在某些数据库上,我认为上述内容可能无法按预期工作(问题是S上的条件是否在LEFT JOIN之前或之后进行了评估。这应该始终有效:

SELECT C.componistId, COUNT(s.componistId)
FROM Componist C LEFT JOIN
     (SELECT S.* FROM Stuk S WHERE S.stuknrOrigineel IS NULL
     ) s
     ON S.componistId = C.componistId AND
GROUP BY C.componistId;

另一种通用解决方案是将条件移动到聚合函数中:

SELECT C.componistId, 
       SUM(CASE WHEN S.stuknrOrigineel IS NULL THEN 1 ELSE 0 END) 
FROM Componist C LEFT JOIN
     Stuk S
     ON S.componistId = C.componistId 
GROUP BY C.componistId;