Sql server sql中的某些记录返回零
我在存储过程中有一个查询,它计算表中的一些记录:Sql server sql中的某些记录返回零,sql-server,Sql Server,我在存储过程中有一个查询,它计算表中的一些记录: SELECT t_Supporter.supporterID, COUNT(t_ticket.ticketID) AS totalTicket FROM t_Supporter INNER JOIN t_ticket ON t_Supporter.supporterID = t_ticket.supporterID_FK WHERE (t_Supporter.orgSectionID_FK = @orgID) GROUP BY t_S
SELECT
t_Supporter.supporterID,
COUNT(t_ticket.ticketID) AS totalTicket
FROM t_Supporter
INNER JOIN t_ticket
ON t_Supporter.supporterID = t_ticket.supporterID_FK
WHERE (t_Supporter.orgSectionID_FK = @orgID)
GROUP BY t_Supporter.supporterID
如果
t\u-Supporter.supporterID
在t\u-ticket
中没有记录,我如何使我的查询返回0您需要使用条件聚合将COUNT
更改为SUM
,并将内部联接
更改为左外部联接
SELECT t_Supporter.supporterID, SUM(CASE WHEN t_ticket.ticketID IS NOT NULL THEN 1 ELSE 0 END) AS totalTicket
FROM t_Supporter LEFT OUTER JOIN
t_ticket ON t_Supporter.supporterID = t_ticket.supporterID_FK
WHERE (t_Supporter.orgSectionID_FK = @orgID)
GROUP BY t_Supporter.supporterID