Skip to content
Advertisement

SQL Query to join multiple tables

I have 4 tables that I need to connect in order to get the reports that I need. But I’m confused on how to write the query. Below are the sample of the tables:

Client Table

client_id  |  client_name  |  con_id
----------:|:-------------:|:-------
    1      |     ABC       |  1
    2      |     DEF       |  1
    3      |     GHI       |  2

Consultant

con_id  |  con_name
-------:|:---------
   1    |    Ani
   2    |   Robby

Perm

pid  |  client_id  |  date
----:|:-----------:|:-----------
 1   |      1      |  2014-08-09
 2   |      1      |  2014-03-02
 3   |      2      |  2014-03-02 

Temp

tid  |  client_id  |  date
----:|:-----------:|:-----------
 1   |     2       |  2013-02-09
 2   |     3       |  2011-03-02
 3   |     3       |  2012-04-02 

The end result of the report that I want to show is something like this:

client_id  |  client_name  |  perm(COUNT)  |  temp(COUNT)  |  con_name
----------:|:-------------:|:-------------:|:-------------:|:---------
    1      |       ABC     |       2       |         0     |    Ani
    2      |       DEF     |       1       |         1     |    Ani
    3      |       GHI     |       0       |         2     |    Robby

I’m trying to use the LEFT OUTER JOIN, but I don’t get the result that I want. Can anyone help me to figure out the query?

Advertisement

Answer

this is a simple outer join query with count and group by,just join your client table with the related ones and count only the distinct associations

select 
c.client_id,
c.client_name,
count(distinct p.pid) perm_count,
count(distinct t.tid) temp_count,
cn.con_name
from client c
left join Consultant cn on(c.con_id = cn.con_id)
left join Perm p on(c.client_id = p.client_id)
left join `Temp` t on(c.client_id = t.client_id)
group by c.client_id 

Fiddle Demo

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement