2017-03-02 54 views
1

MS SQL Server中,表1COALESCE用於連接

comment_no  comment 
1    excellent 
2    ok 
3    acceptable 

表2

name service_comment quality_comment quantity_comment 
shop1 0     0    1 
shop2 0     2    0 
shop3 1     0    0 

結果表將

name service_comment quality_comment quantity_comment comment 
shop1 0     0    1     Excellent 
shop2 0     2    0    good 
shop3 1     0    0    excellent 

我怎麼合併兩個表一起?因爲每個商店都需要註釋詳細信息。感謝

+0

如果有什麼的三個值1,2,3?如果是3,2,1呢? – GurV

+3

對我來說,你爲這個查詢而苦苦掙扎的原因是因爲你的表格設計有缺陷。你的table2應該有一個列表明它是哪種類型的評論。 –

回答

2

對於你提出的數據,你可以使用left join和合並:

select t1.*, 
     coalesce(t2s.comment, t2ql.comment, t2qn.comment) as comment 
from t1 left join 
    t2 t2s 
    on t1.service_comment = t2s.comment_no left join 
    t2 t2ql 
    on t1.quality_comment = t2ql.comment_no left join 
    t2 t2qn 
    on t1.quantity_comment = t2qn.comment_no; 

如果你可以有多個註釋,那麼你可能會喜歡:

select t1.*, 
     trim('; ' from (coalesce('; ' + t2s.comment, '') + 
         (coalesce('; ' + t2ql.comment, '') + 
         (coalesce('; ' + t2qn.comment, '') 
        ) 
     ) as comment 
from t1 left join 
    t2 t2s 
    on t1.service_comment = t2s.comment_no left join 
    t2 t2ql 
    on t1.quality_comment = t2ql.comment_no left join 
    t2 t2qn 
    on t1.quantity_comment = t2qn.comment_no; 
+0

非常感謝您的幫助。有用。 – Ann