2017-07-06 85 views
0

我想使用聯合將計劃和實際數據合併到1個視圖中。 爲此,我使用兩個內部聯接來使行匹配 - 然後我使用union語句。目前,我通過3個步驟完成此操作 - 現在我想將所有這些合併爲1步。如何在聯合聲明中包含2個聯接

創建vPlan2

Select 
    a.step, 
    a.[planned user], 
    b.[actual user], 
    a.[invoice plan] as 'invoice' 
from vPlan a 
inner join vActuals b on a.step = b.step 
group by 
    a.step, 
    a.[planned user], 
    b.[actual user], 
    a.[invoice plan] 

創建vActuals2

Select 
    a.step, 
    b.[planned user], 
    a.[actual user], 
    a.[invoice actuals] as 'invoice' 
from vActuals a 
inner join vPlan b on a.step = b.step 
group by 
    a.step, 
    a.[actual user], 
    b.[planned user], 
    a.[invoice actuals] 

創建vplanandactuals

select 
    'Plan' as type, 
    a.step, 
    a.[planned user], 
    a.invoice, 
    a.[actual user] 
from vPlan2 a 
group by 
    a.step, 
    a.[planned user], 
    a.invoice, 
    a.[actual user] 
Union 
select 
    'Actuals', 
    b.step, 
    b.[planned user], 
    b.invoice, 
    b.[actual user] 
from vActuals2 b 
group by 
    b.step, 
    b.[planned user], 
    b.invoice, 
    b.[actual user] 
+1

怎麼了所有的分組?沒有聚合。你有什麼錯誤或問題? – scsimon

+0

你的問題是什麼?爲什麼左連接標籤?你的工會爲什麼不足? – philipxy

回答

1

我想你在找什麼是:

Select 
    'Plan' as Type, 
    a.step, 
    a.[planned user], 
    b.[actual user], 
    a.[invoice plan] as 'invoice' 
from vPlan a 
inner join vActuals b on a.step = b.step 
group by 
    a.step, 
    a.[planned user], 
    b.[actual user], 
    a.[invoice plan] 

union all 

Select 
    'Actuals' as Type, 
    a.step, 
    b.[planned user], 
    a.[actual user], 
    a.[invoice actuals] as 'invoice' 
from vActuals a 
inner join vPlan b on a.step = b.step 
group by 
    a.step, 
    a.[actual user], 
    b.[planned user], 
    a.[invoice actuals] 
2

類似@ texastonie的回答,但更換group byselect distinct

Select Distinct 
    'Plan' as type, 
    vPlan.step, 
    vPlan.[planned user], 
    vPlan.[invoice plan] as 'invoice', 
    vActuals.[actual user] 
from vPlan 
inner join vActuals 
    on vPlan.step = vActuals.step 
union 
Select Distinct 
    'Actuals' as type, 
    vActuals.step, 
    vPlan.[planned user], 
    vActuals.[invoice actuals] as 'invoice', 
    vActuals.[actual user] 
from vActuals 
inner join vPlan 
    on vActuals.step = vPlan.step 
; 
+0

肯定應該使用不同的分組。我想知道我們是否真的需要一個獨特的。 – theo