这是我遇到的问题的一个非常简单的例子。上面的TableA和TableB表示来自更大表的查询。
JOB | DELIVERED
0001 | 1000
0002 | 500
0003 | 1000
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
JOB | DELIVERED | REJECTS
0001 | 1000 | 6
0002 | 500 | 8
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
JOB | DELIVERED | REJECTS
0001 | 1000 | 6
0002 | 500 | 8
0003 | 1000 |
答案 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