Home > Blockchain >  Join three tables to get matched and unmatched data
Join three tables to get matched and unmatched data

Time:08-10

I have below 3 tables.

Table 1: Invoice

Columns - ID,SPENT,ROLEID

ID | SPENT | ROLEID

1  | 500   |  1
2  | 400   |  2

Table 2: ROLES

Columns - ROLE_ID (PK),DEPARTMENT_ID,ROLE_NAME

ROLE_ID | DEPARTMENT_ID | ROLE_NAME

1       |    1          | AGENT
2       |    2          | SUPERVISOR

Table 3: DEPARTMENT

Columns - DEP_ID,DEP_NAME

DEP_ID | DEP_NAME

1   | ACCOUNTING 
2   | CUSTOMER_SERVICE
3   | HRA

The final output is that if I look for the invoices, I should see all the departments even when I just got a invoices for 1 department.

Below is the query which I tried.

SELECT
       D.DEP_NAME
      ,I.SPENT
FROM INVOICE I 
CROSS JOIN DEPARTMENT D
LEFT JOIN ROLES R ON R.ROLE_ID = I.ROLE_ID AND D.DEP_ID = R.DEPARTMENT_ID
ORDER BY D.DEP_NAME

Example output:

 DEP_NAME        | SPENT
    
ACCOUNTING       | 500
CUSTOMER_SERVICE | 400
HRA              | NULL

Above query is giving me duplicate data and also I'm not getting the unmatched values.

Can anyone please advise on this?

CodePudding user response:

SELECT
D.DEP_NAME
, SUM(I.SPENT) as 'SPENT'
FROM DEPARTMENT D
LEFT JOIN ROLES R on R.DEPARTMENT_ID = D.DEP_ID 
LEFT JOIN INVOICE I on I.ROLE_ID = R.ROLE_ID
GROUP BY D.DEP_NAME
ORDER BY D.DEP_NAME

Since you don't want duplicates you have to group on the department name and take the SUM of the SPENT field from the INVOICE table since you can have multiple invoices per department.

CodePudding user response:

To get all the departments in the output, Department table should be the base table in query. This should be the correct query :

select D.DEP_NAME, I.SPENT from DEPARTMENT D
left join ROLES R on D.DEP_ID = R.DEPARTMENT_ID
left join Invoice I on R.ROLE_ID = I.ROLEID

enter image description here

  • Related