当我加入包含求和函数的2个不均匀表时,如何获取所有数据?

时间:2018-02-07 21:07:41

标签: sql join sum missing-data

这是我遇到的问题的一个非常简单的例子。上面的TableA和TableB表示来自更大表的查询。

TableA

 JOB | DELIVERED
0001 |      1000
0002 |       500
0003 |      1000

TableB

 JOB | DEFECT | QTY
0001 |      A |   2
0001 |      B |   1
0001 |      C |   3
0002 |      A |   1
0002 |      B |   5
0002 |      C |   2

如果我写声明

SELECT 
    TableA.JOB, 
    TableA.DELIVERED, 
    sum(TableB.QTY) AS REJECTS 
from 
    TableA LEFT JOIN TableB ON 
        (TableA.JOB = TableB.JOB) 
GROUP BY 
    TableA.JOB, 
    TableA.DELIVERED

I get the result

 JOB | DELIVERED | REJECTS
0001 |      1000 |       6
0002 |       500 |       8

What I actually want is

 JOB | DELIVERED | REJECTS
0001 |      1000 |       6
0002 |       500 |       8
0003 |      1000 |       0

如何让它给我想要的东西?我找到了一个解决方案,但这对我来说似乎不合理,而且在实践中花了太长时间。

SELECT 
    TableD.JOB, 
    TableD.DELIVERED, 
    TableC.REJECTS 
FROM 
    TableA TableD LEFT JOIN (
        SELECT 
            TableA.JOB, 
            sum(TableB.QTY) AS REJECTS 
        from 
            TableA TableA INNER JOIN TableB TableB ON 
                (TableA.JOB = TableB.JOB) 
        GROUP BY TableA.JOB) TableC

This statement gives

 JOB | DELIVERED | REJECTS
0001 |      1000 |       6
0002 |       500 |       8
0003 |      1000 |

1 个答案:

答案 0 :(得分:0)

假设您正在使用SQL Server 2008,请尝试isnull函数,如下所示:

SELECT TableD.JOB, TableD.DELIVERED, isnull(TableC.REJECTS,0)
FROM TableA, TableD 
LEFT JOIN (select TableA.JOB, sum(TableB.QTY) AS REJECTS from TableA
           inner join TableB on (TableA.JOB = TableB.JOB) 
           group by TableA.JOB) TableC