我想计算每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行的行。我怎样才能做到这一点?
答案 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 JOIN
与COUNT()
合并时的所需内容。
在某些数据库上,我认为上述内容可能无法按预期工作(问题是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;