大于0时连接值

时间:2015-05-04 17:52:07

标签: sql sql-server database concatenation

如果值大于0,我需要连接多列的值。

示例:

Video     1  
Internet  0  
Phone     3  
Security  0  
Basic     1  

因此结束值为1 Video|3 Phone|1 Basic|

有没有比写代码更好的方法呢?

    Case When Video > 0 and Internet+Phone+Security+Basic < 0 Then Video + ' Video|' 
    When Video > 0 and Internet > 0 and Phone+Security+Basic < 0 Then Video + ' Video|' + Internet + ' Internet|' 
    When Video > 0 and Phone > 0 and Internet+Security+Basic < 0 Then Video + ' Video|' + Phone + ' Phone|'

等等,直到考虑到每个组合。

1 个答案:

答案 0 :(得分:5)

select
  Case When Video > 0     Then Video +     ' Video|'     else '' end +
  Case When Internet  > 0 Then Internet  + ' Internet|'  else '' end +
  Case When Phone > 0     Then Phone +     ' Phone|'     else '' end +
  Case When Security > 0  Then Security +  ' Security|'  else '' end +
  Case When Basic > 0     Then Basic +     ' Basic|'     else '' end +
from source