SQL Query for joining multiple tables
I have 4 tables that I need to connect to get the reports I need. But I am confused about how to write the query. Below are examples of tables:
Customer 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
Permian
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 I want to show looks 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 am trying to use LEFT OUTER JOIN
but I am not getting the result I want. Can anyone help me sort out the request? thanks in advanced state.
source to share
this is a simple outer join query with count and group by, just join the table client
with related ones and only count the individual 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
source to share
You have to join the whole table with an allig query in one sql.See link http://www.w3resource.com/sql/joins/using-a-where-cluase-to-join-two-tables-related-by-a -single-column-primary-key-or-foriegn-key-pair.php
SELECT a.client_id as client_id, a.client_name as client_name,
a.con_id as client_con_id,
b.con_id as con_id,
b.con_name as con_name,
c.pid as perm_id,
c.client_id as perm_client_id
c.date as perm_date
d.tid as temp_id,
d.client_id as tem_client_id
.... Anything you want to choose ....
from client_table a
Inner join Consultant_table b on a.client_con_id = b.con_id
Inner join perm_table c on a.client_id= c.perm_client_id
Inner join Temp_table d on....
source to share