Monday, October 5, 2015

sql - Side by side counts from multiple tables

I had to create a daily report with counts from different tables in SQL Server.The report had counts for total rows in tables for a given day.Below is the sql to get counts from 7 different tables and display the counts in separate columns for a given day in the month.

select a.create_dt,con,bro,[set],conf,demo,vip,dev
from 
(select create_dt,count( id) con,row_number() over (order by create_dt) as row_num 
from table1 with (nolock)
group by create_dt
) a 
full outer join
(select create_dt,count( id) demo,row_number() over (order by create_dt) as row_num
from table2 with (nolock)
group by create_dt
) b
on a.row_num = b.row_num
full outer join
(select create_dt,count( id) bro,row_number() over (order by create_dt) as row_num
from table3 with (nolock)
group by create_dt
) c
on b.row_num = c.row_num
full outer join
(select create_dt,count(id) [set],row_number() over (order by create_dt) as row_num
from table4 with (nolock)
group by create_dt
) d
on c.row_num = d.row_num
full outer join
(select create_dt,count(id) vip,row_number() over (order by create_dt) as row_num
from table5 with (nolock)
group by create_dt
) e
on d.row_num = e.row_num
full outer join
(select create_dt,count(id) dev,row_number() over (order by create_dt) as row_num
from table6 with (nolock)
group by create_dt
) f
on e.row_num = f.row_num
full outer join
(select convert(varchar(8),create_ts,112) create_dt,count(id) conf,row_number() over (order by convert(varchar(8),create_ts,112)) as row_num
from table7 with (nolock)
group by convert(varchar(8),create_ts,112)
) g
on f.row_num = g.row_num
order by a.create_dt




No comments: