繁体   English   中英

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

[英]Join Two Select Statements With Different Columns And Condition

我不擅长提问,所以我举一个我想拥有的例子。

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

如果它们的列不相等并且都具有唯一条件,那么如何加入2 select语句?

根据条件,您可以创建派生表以获取所需的列,然后获得两个表的并集,在列数较少的派生表的列列表中添加空值:

伪代码:

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

希望这可以帮助!!!

如果不是不使用动态sql的要求,我将选择该选项。

另一个想法是使用用户定义的函数returnin表。

因此,您将逻辑封装在那里...

暂无
暂无

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

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