基于多列之一加入

时间:2017-03-02 17:03:30

标签: sql sql-server join

我正在使用SQL Server。

表1

comment_no   comment 
1            excellent 
2            ok
3            acceptable 

table2

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 

如何加入这两个表来获得此结果?

1 个答案:

答案 0 :(得分: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;