简体   繁体   中英

How do I get all data when I join 2 uneven tables with a sum function involved?

Here is a very simplified example of the problem I am having. TableA and TableB above represent queries from a larger table.

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

If I write the statement

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

How do I get it to give me what I want? I found a solution, but it seems unreasonable to me and in practice takes too long.

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 |

Assuming you are working on SQL Server 2008, try isnull function like below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM