我有以下SQL选择所有ManifestoBatches并给我一个每个批次项目的计数(ManifestoItems):
SELECT m.Id, u.UserName, m.TotalRows, m.DateCreated, count(i.Id) as Items
FROM ManifestoBatches as m
left join ManifestoItems as i on m.Id = i.BatchId
inner join AmzUsers as u on m.CreatedBy = u.Id
GROUP BY m.Id
ORDER BY Items DESC
LIMIT 0, 10
这很好用;但是,我想只计算具有ManifesoItems.ScannerId属性不等于null的ManifestoItems。
所以,我尝试添加这个:
where NULLIF(i.ScannerId, '') is not null
但是,这会过滤整个结果集,只给我ManifestoBatches,其中ManifestoItems.ScannerId不为空。 相反,我希望它能获得所有ManifestoBatches,但只给我一些ManifestoItems,其中ManifestoItems.ScannerId不为空。
我该怎么做?
答案 0 :(得分:2)
我认为您的问题是left join
。当值不匹配时,这会生成NULL
。但听起来你在场上有NULL
值。这可以解决您的问题:
SELECT m.Id, u.UserName, m.TotalRows, m.DateCreated, count(i.Id) as Items
FROM ManifestoBatches m join
ManifestoItems i
on m.Id = i.BatchId inner join
AmzUsers u
on m.CreatedBy = u.Id
WHERE i.ScannerId is not null
GROUP BY m.Id
ORDER BY Items DESC
LIMIT 0, 10;
如果您仍然需要left join
,请将逻辑移至count()
:
SELECT m.Id, u.UserName, m.TotalRows, m.DateCreated, sum(i.ScannerId is not null) as Items
FROM ManifestoBatches m left join
ManifestoItems i
on m.Id = i.BatchId inner join
AmzUsers u
on m.CreatedBy = u.Id
GROUP BY m.Id
ORDER BY Items DESC
LIMIT 0, 10;
答案 1 :(得分:1)
添加
sum(i.ScannerId is not NULL)
选择。
答案 2 :(得分:1)
而不是
count(i.Id)
使用
SUM(CASE WHEN i.ScannerId IS NOT NULL THEN 1 ELSE 0 END)`