Reputation: 821
I want to join multiple views with uneven data. Let me explain with sample data
View1:
DATE | COL2
150 rows
View2:
DATE | COL3
30 rows
View3:
DATE | COL4
15 rows
so i want to get data like:
OUTPUT:
DATE | COL2 | COL3 | COL4
150 rows with nulls on some columns
DATE column is MONTH:YEAR like 02/2019. Each view made with DATEPART MONTH and YEAR columns and gathered in a single column. So i don't want to have duplicated DATE rows.
Upvotes: 1
Views: 42
Reputation: 1269633
In SQL Server, you can use full join
:
select coalesce(v3.date, v2.date, v1.date) as date, v1.col2, v2.col3, v3.col4
from view1 v1 full join
view2 v2
on v2.date = v1.date full join
view3 v3
on v3.date = coalesce(v2.date, v1.date);
This is preferable to a left join
solution because each view is accessed only once, so any code in the view is not run multiple times.
Upvotes: 1
Reputation: 133360
You could use left join base on the union of the date
select t1.date, v1.COL2, v2.COL3, v3.COL4
from(
select date from view1
union
select date from view2
union
select date from view2
) t1
left join view1 v1 on t1.date = v1.date
left join view2 v2 on t1.date = v2.date
left join view1 v3 on t1.date = v3.date
Upvotes: 2