简体   繁体   English

连接具有不同列和条件的两个选择语句

[英]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? 如果它们的列不相等并且都具有唯一条件,那么如何加入2 select语句?

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. 如果不是不使用动态sql的要求,我将选择该选项。

Another idea will be to use user defined function returnin tables. 另一个想法是使用用户定义的函数returnin表。

So you encapsulate there the logic... 因此,您将逻辑封装在那里...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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