当没有匹配

时间:2015-08-12 18:33:17

标签: sql join

我正在编写一个存储过程,将计数添加到两个字段。我有以下代码:

    SELECT Distinct DateTime1,SUM(TICKETREQ1)SUMREQ, SUM(TicketPU1)SUMPU1, (count(*))AS GRADCOUNT
    FROM TABLEA
    WHERE YEAR = '2015'
        AND TicketReq1 > 0
        group by DateTime1

    Select DISTINCT(DateTime2),SUM(TicketReq2) SUMREQ,SUM(TicketPU2)SUMPU2, (count(*))AS GRADCOUNT
    from TABLEA
    where TicketReq2 > 0
        and YEAR = '2015'
        Group by DateTime2;


SELECT Distinct c.DateTime1,SUM(c.TICKETREQ1 + b.TicketReq2)SUMREQ, SUM(c.TicketPU1 + b.TicketPU2)SUMPU1, (count(b.id) + count(c.id))AS GRADCOUNT
FROM TABLEA c
LEFT JOIN TABLEA b 
    ON (b.DateTime2 = c.DateTime1
    AND b.TicketReq2 > 0
    AND b.YEAR = '2015')
WHERE c.YEAR = '2015'
AND c.TicketReq1 > 0
group by c.DateTime1

返回:
enter image description here

对于某些仪式,第二个查询会引入结果并正确添加它们。但如果没有记录,那就失败了。

enter image description here


如何让它一起加入两个计数(查询1和2),以便即使没有匹配,查询3也会显示两个计数

2 个答案:

答案 0 :(得分:1)

问题是查询#3上的type || total || id || value 1 || 9|10 || 1,2|3 || 10-20,21-30|31-40 2 || 9|8 || 4,5|6 || 41-50,51-60|61-70 语句。 SUM为空,因此b.TicketReq2会遇到错误。尝试在SUM(c.TICKETREQ1 + b.TicketReq2)函数调用中使用ISNULL(b.TicketReq2, 0)

答案 1 :(得分:0)

尝试完全外连接而不是左连接

SELECT Distinct c.CeremonyDateTime1,SUM(c.TICKETREQ1 + b.TicketReq2)SUMREQ, SUM(c.TicketPU1 + b.TicketPU2)SUMPU1, (count(b.gid) + count(c.gid))AS GRADCOUNT
FROM ComTicket c
FULL OUTER JOIN ComTicket b 
ON (b.CeremonyDateTime2 = c.CeremonyDateTime1
AND b.TicketReq2 > 0
AND b.Gradterm = '201540')
WHERE c.gradterm = '201540'
AND c.TicketReq1 > 0
group by c.CeremonyDateTime1

这对你有帮助..