简体   繁体   中英

How to join multiple uneven views

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.

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 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM