Select datas from multiple tables using one common table in sql server 2005 -
i have many tables , 1 common table have ids of these tables eg:
table1
| id | value | date | --------------------------- | 1 | 200 | 25/04/2013 | | 2 | 250 | 26/05/2013 |
table2
| id | value | date | --------------------------- | 1 | 300 | 25/05/2013 | | 2 | 100 | 12/02/2013 |
table3
| id | value | date | --------------------------- | 1 | 500 | 5/04/2013 | | 2 | 100 | 1/01/2013 |
and 1 common table
| id | table | tableid | ------------------------- | 1 | table1 | 1 | | 2 | table3 | 1 | | 3 | table2 | 1 | | 4 | table1 | 2 | | 5 | table2 | 2 | | 6 | table3 | 2 |
and using common table need select datas in above 3 tables eg:
output id table tableid value date 1 table1 1 200 25/04/2013 2 table3 1 500 5/04/2013 3 table2 1 300 25/05/2013 4 table1 2 250 26/05/2013 5 table2 2 100 12/02/2013 6 table3 2 100 1/01/2013
if don't want use union all
can use coalesce
same using left join
this:
select c.* , coalesce(t1.value, t2.value,t3.value) value , coalesce(t1.date, t2.date,t3.date) date common c left join table1 t1 on c.tableid = t1.[id] , [table] = 'table1' left join table2 t2 on c.tableid = t2.[id] , [table] = 'table2' left join table2 t3 on c.tableid = t3.[id] , [table] = 'table3' order id;
see this sqlfiddle
by way can reduce task join records using union all
. given data structure have join tables anyhow.
Comments
Post a Comment