简体   繁体   中英

Join Two Select Statements With Different Columns And Condition

I'm not good at asking question, so i'll give an example of what i want to have.

if i = 1 and xi = 0 then
    select a,b,c,d,e,f,g where z = 1
elseif i=0 and xi = 1 then
    select a,c,f,h,l,n where w = var
elseif i=1 and xi=1 then
    select a,b,c,d,e,f,g, where z = 1
    union all
    select a,c,f,h,l,n where w = var
end if

How can I join the 2 select statement if their columns are not equal and they both have a unique condition?

Based on the conditions you can create derived tables to fetch desired columns and then to get a union of the two tables add null values in column list of derived tables which have less number of columns:

Pseudo code:

select * from 
(select a,b,c,d,e,f,g
 where  z = 1 
 and 1 = case when i = 1 and xi = 0 then 1 
             when i = 1 and xi = 1 then 1
             else 0 
        end) as T1
 union all             
(select a,c,f,h,l,n ,null -- add null value to equate number of columns
where w = var 
and 1 = case when i=0 and xi = 1 then 1 
             when i=1 and xi = 1 then 1
             else 0 
        end) as T2

Hope this helps!!!

If it is not a requirement not to use dynamic sql I will opt for that one.

Another idea will be to use user defined function returnin tables.

So you encapsulate there the logic...

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