2014-08-28 88 views
1

你好,我有以下場景: 我有一個事實表有4個關鍵字段和1個關鍵字段的Dim表,我必須將事實表加入到基於暗表的表在所有這些關鍵領域尋找某種類型的醫生。你能指導我如何去做這件事。謝謝。基於多個關鍵字段加入兩個表

Provider_Fact: ADMITTINGDoc, ATTENDINGDoc, REFERRINGDoc, TREATINGDoc

Provider_Dim: ID, 名稱

+0

你可以發佈一些示例數據和預期的結果? – KrazzyNefarious 2014-08-28 16:40:02

回答

2

取決於你想如何看待它。根據你的問題,我不完全清楚。也許:

SELECT ad.NAME as AdmittingDocName, 
at.NAME as AttendingDocName, 
re.NAME as ReferringDocName, 
tr.NAME as TreatingDocName 
FROM Provider_Fact pf 
JOIN Provider_Dim ad 
    on ad.ID = pf.AdmittingDoc 
JOIN Provider_Dim at 
    on ad.ID = pf.AttendingDoc 
JOIN Provider_Dim re 
    on ad.ID = pf.ReferringDoc 
JOIN Provider_Dim tr 
    on ad.ID = pf.TreatingDoc 

OR

SELECT pd.ID, pd.NAME 
FROM Provider_Fact pf 
JOIN Provider_Dim pd 
    on ad.ID = pf.AdmittingDoc 
WHERE name = @name 
union 
SELECT pd.ID, pd.NAME 
FROM Provider_Fact pf 
JOIN Provider_Dim pd 
    on ad.ID = pf.AttendingDoc 
WHERE name = @name 
union 
SELECT pd.ID, pd.NAME 
FROM Provider_Fact pf 
JOIN Provider_Dim pd 
    on ad.ID = pf.ReferringDoc 
WHERE name = @name 
union 
SELECT pd.ID, pd.NAME 
FROM Provider_Fact pf 
JOIN Provider_Dim pd 
    on ad.ID = pf.TreatingDoc 
WHERE name = @name 

:)

+0

您在第一次查詢時出錯 - 當您加入到Provider_Dim的多個別名時,您需要爲每個別名使用每個alias.ID而不是ad.ID,這只是第一個別名。所以ad.ID = pf.AdmittingDoc爲第一個,pd.ID = pf.AttendingDoc,re.ID = pf.ReferringDoc和tr.ID = pf.TreatingDoc。 PS - 如果你解決它,評論和包括我的名字,所以我看到它的標記,我會打勾你抵消誰給你的答案downvote誰。 – 2014-08-28 17:40:50