2017-03-03 115 views
1

讓我先說我是初學者,隨時隨地讓查詢看起來更好,因爲您認爲合適。無論如何,我無法將所有的兩個查詢結合起來,我認爲這比將兩者結合到一個表格更容易。我嘗試了一個聯合,但這只是從第一個查詢返回列。我想要完成的是通過使用TrainProgram將第一個查詢與第二個查詢結合起來。 UserLastName是我真正需要的一列,但它並不知道。任何幫助將不勝感激。謝謝。這是第一個查詢:將兩個SQL查詢合併到一個整潔表中

select 
    aa.TrainProgramID 
    , aa.TrainProgram_OrganizationalUnitName 
    , aa.TrainProgramMetaDataTypeName 
    , aa.TrainProgramName 
    , a.Activity_Name 
    , a.Activity_Duration 
    , a.Activity_UpdateDate 
    , i.EntityName  as [MPN] 
    , a.Activity_TypeName as [Activity_MDT] 
    , g.Activity_ID 
    , a.Activity_Description 
    , a.ActivityPar_SNa as [ActivitySName] 
    , a.Activity_Order 
    , a.ActivityPar_SID as [ActivitySID] 
from rawViews.MCD_DH_Activities a 
    left join rawViews.MCD_DH_TrainingProgramsBasicData aa 
    on a.Activity_EntityID = aa.TrainingProgramID 
    inner join dh.MCD_DH_Activities g 
    on g.Activity_ID = a.Activity_ID 
    full join rawViews.MCD_DH_ActivityPrerequisites h 
    on h.ActivityID = a.Activity_ID 
    left join dh.MCD_DH_BaseEntities i 
    on a.Activity_EntityID = i.EntityID 
where a.Activity_VersionStatusID = 1 

這裏是我的第二個查詢:

select 
    b.TrainProgramID 
    , c.uid 
    , c.UserLastName 
from dh.MCD_DH_UserTrainProAssoc a 
    inner join rawViews.MCD_DH_TrainProgramsBasicData b 
    on a.TrainProgramID = b.TrainProgramID 
    inner join rawViews.MCD_DH_UBasicData c 
    on a.uid = c.uid 
+0

你嘗試加入? –

+0

[踢壞的習慣:使用(a,b,c)或(t1,t2,t3)這樣的表別名 - Aaron Bertrand](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08 /bad-habits-to-kick-using-table-aliases-like-abc-or-t1-t2-t3.aspx) – SqlZim

回答

2

我認爲這是你在找什麼:

select 
    aa.TrainProgramID 
    , aa.TrainProgram_OrganizationalUnitName 
    , aa.TrainProgramMetaDataTypeName 
    , aa.TrainProgramName 
    , c.uid 
    , c.UserLastName 
    , a.Activity_Name 
    , a.Activity_Duration 
    , a.Activity_UpdateDate 
    , i.EntityName  as [MPN] 
    , a.Activity_TypeName as [Activity_MDT] 
    , g.Activity_ID 
    , a.Activity_Description 
    , a.ActivityPar_SNa as [ActivitySName] 
    , a.Activity_Order 
    , a.ActivityPar_SID as [ActivitySID] 
from rawViews.MCD_DH_Activities a 
    left join rawViews.MCD_DH_TrainingProgramsBasicData aa 
    on a.Activity_EntityID = aa.TrainingProgramID 
    left join dh.MCD_DH_UserTrainProAssoc utpa 
    on aa.TrainProgramID = utpa.TrainProgramID 
    left join rawViews.MCD_DH_UBasicData c 
    on utpa.uid = c.uid 
    inner join dh.MCD_DH_Activities g 
    on g.Activity_ID = a.Activity_ID 
    full join rawViews.MCD_DH_ActivityPrerequisites h 
    on h.ActivityID = a.Activity_ID 
    left join dh.MCD_DH_BaseEntities i 
    on a.Activity_EntityID = i.EntityID 
where a.Activity_VersionStatusID = 1 
+0

謝謝!這就說得通了。 :) – BoyGeorge

+0

@BoyGeorge樂意幫忙! – SqlZim

+0

@SQLZim混合這樣的內部和外部連接可能會導致一些數據意外。內連接之前的左連接很可能會變成內連接。由於G正在加入A,所以最好在查詢中進行第一次加入。 從 內上克加入克 =一個 上留下= AA 加入AA 留在AA加入UTPA = UTPA 留在UTPA將C = C 左側上的連接我 = I 完全加入h h = a –