2010-01-24 48 views
0

我希望有人能幫助我。T-SQL視圖選擇FULL OUTER JOIN並在「A」基於「B」表添加其他行

我需要解決一個問題,在下面的場景中爲我提供正確的結果。

我有兩個表:LanguageReportDescription

語言

Id Tag Description 
---- ---- ---------------- 
1 en English  
2 de German 
3 fr French 
4 it Italian 

ReportDescription

LanguageId ReportId Description 
---------- ----------- ------------------- 
1   1   Committee of (Eng) 
2   1   Committee of (German) 
3   1   Committee of (French) 
4   1   Committee of (Ita) 
1   2   Appointment of (Eng) 

我想有結果將是:

LanguageId ReportId Description 
---------- ----------- ------------------- 
1   1   Committee of (Eng) 
2   1   Committee of (German) 
3   1   Committee of (French) 
4   1   Committee of (Ita) 
1   2   Appointment of (Eng) 
2   2   Appointment of (Eng) 
3   2   Appointment of (Eng) 
4   2   Appointment of (Eng) 

任何幫助將不勝感激。

+0

爲什麼結果有一行意大利語「預約(Eng)」? – Andomar 2010-01-24 11:46:45

+2

如果您以散文形式描述您對結果集的描述,可能會有所幫助。現在我不太清楚...... – 2010-01-24 11:50:10

+0

@Paul:同意。產生結果的邏輯是什麼3.至少有兩種方法可以做到這一點,但如果沒有邏輯,任何解決方案在其他情況下都失敗 – gbn 2010-01-24 13:36:23

回答

0

這一個返回你描述的結果,希望這就是你想要的。

如果該條目不存在於ReportDescription中,則需要FallbackDescription

SELECT 
    l.id LanguageId, r.ReportId, 
    COALESCE(rd.Description, r.FallbackDescription) Description 
FROM language l 
JOIN (SELECT ReportId, MIN(Description) FallbackDescription 
     FROM ReportDescription 
     GROUP BY ReportId) r ON (1 = 1) 
LEFT JOIN ReportDescription rd ON (rd.Id = l.Id AND rd.ReportId = r.ReportId) 
ORDER BY ReportId, LanguageId 
0

如果你正在尋找的是一個默認的報告時especific語言不可用,此查詢將做到這一點:

SELECT rd.LanguageId, rd.ReportId, 
COALESCE(r.Description, 
    (SELECT Description FROM ReportDescription 
    WHERE ReportDescription.ReportId = rd.ReportId AND LanguageId = 1)) AS Description 
FROM (SELECT DISTINCT ReportId, l.Id AS LanguageId FROM ReportDescription, Language l) rd 
LEFT JOIN ReportDescription r ON rd.LanguageId = r.LanguageId AND rd.ReportId = r.ReportId 
ORDER BY rd.ReportId, rd.LanguageId 

的默認語言似乎是你的問題的英語(不忘記添加西班牙語支持;-))。