[英]SQL LEFT OUTER JOIN with Count
我在這里有此查詢:
SELECT a.timeSlot, a.dateSlot, COUNT(concat(b.dateSlot, ' - ', b.timeSlot)) AS counter
FROM CP_VIP_Preview_TimeSlots as a
LEFT OUTER JOIN [CP-VIP-Preview] as b
ON a.timeSlot = b.dateSlot
AND a.dateSlot = b.timeSlot
GROUP BY a.timeSlot, a.dateSlot, a.[order]
ORDER BY a.[order]
我想做的是獲取每個查詢的計數,但是查詢有些混亂,任何具有0的行都顯示為1,而實際上具有項目的任何行都顯示正確的數字,如果該行存在問題count是0,它顯示1.。為什么這樣做?
您的COUNT(concat(b.dateSlot, ' - ', b.timeSlot))
將始終返回至少一個
也許你可以嘗試
sum(IIF(b.dateSlot is null,0,1))
您需要使用HAVING在使用分組依據之后應用過濾器,這樣就不會將記錄計數為零
SELECT a.timeSlot, a.dateSlot, COUNT(concat(b.dateSlot, ' - ', b.timeSlot)) AS counter
FROM CP_VIP_Preview_TimeSlots as a
LEFT OUTER JOIN [CP-VIP-Preview] as b
ON a.timeSlot = b.dateSlot
AND a.dateSlot = b.timeSlot
GROUP BY a.timeSlot, a.dateSlot, a.[order]
ORDER BY a.[order]
HAVING COUNT(concat(b.dateSlot,'-',b.timeSlot))> 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.