[英]Group by count zero rows not displaying
I want to count the amount of rows of every componistId
.我想计算每个componistId
的行componistId
。 When I run the following SQL statement it works fine:当我运行以下 SQL 语句时,它工作正常:
SELECT C.componistId, COUNT(*)
FROM Componist C LEFT JOIN Stuk S ON S.componistId = C.componistId
GROUP BY C.componistId
Now I want only the rows where stukNrOrigineel
is null现在我只想要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
But when I do this, all the rows with a result of 0 disappear.但是当我这样做时,结果为 0 的所有行都消失了。 Only the rows with at least 1 row are displayed.仅显示至少有 1 行的行。 How can I make this work?我怎样才能使这项工作?
You need to include the condition in the on
clause:您需要在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;
Note: I changed the COUNT()
to count from the second table.注意:我将COUNT()
更改为从第二个表中进行计数。 This is normally what you want when combining LEFT JOIN
with COUNT()
.这通常是将LEFT JOIN
与COUNT()
结合使用时所需要的。
On some databases, I think the above might not quite work as expected (the question is whether the condition on S
is evaluated before or after the LEFT JOIN
).在某些数据库上,我认为上述内容可能无法按预期工作(问题是S
上的条件是在LEFT JOIN
之前还是之后评估)。 This should always work:这应该始终有效:
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;
Another generic solution is move the condition into the aggregation function:另一个通用解决方案是将条件移动到聚合函数中:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.