2017-03-02 49 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