簡體   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