2016-10-20 23 views
0

JOIN我有這個疑問在這裏:SQL LEFT OUTER以計數

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,任何實際上有一個項目的行都顯示正確的編號,如果行計數爲0,則顯示1 ....爲什麼這樣做?

+0

如果您試圖從b計數非空值,請停止使用CONCAT,因爲即使對於不匹配的行也不會返回NULL,或者兩個輸入都爲NULL。比較'SELECT COUNT(CONCAT(NULL,'。'));''到'SELECT COUNT(NULL +'。');' –

回答

2

COUNT(concat(b.dateSlot, ' - ', b.timeSlot))總是返回至少一個

或許你可以嘗試

sum(IIF(b.dateSlot is null,0,1)) 
+0

它會返回1但不是因爲它是一個計數,而是因爲CONCAT不允許任何NULL輸出。如果你停止使用CONCAT,你可以得到0。我更喜歡SUM/IsNull,但要小心:如果dateSlot是日期/時間列,則0將轉換1900-01-01,這將打破您的SUM。使用'COUNT(b.dateSlot +' - '+ b.timeSlot)',或者使用'CASE'表達式,會更可靠。 –

+0

@AaronBertrand糾正。謝謝你的收穫 –

-1

你需要使用一個具有通過使用後組應用過濾器,這樣,你不要指望記錄爲零

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

+0

我試着添加HAVING,但它沒有工作,它顯示1當它的0 – user979331