SQL LEFT OUTER JOIN with Count

时间:2016-10-20 20:10:56

标签: sql sql-server tsql

I have this query here:

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]

What I am trying to do is get a count of each, which this query does, but something is messed up, any rows that have 0 appear as 1 and any row that actually has an items show the correct number, my problem if the row count is 0 its displaying 1....why is it doing that?

2 个答案:

答案 0 :(得分:2)

您的COUNT(concat(b.dateSlot, ' - ', b.timeSlot))将始终返回至少一个

也许你可以试试

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

答案 1 :(得分:-1)

你需要在使用group by之后使用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