将列合并到一列SQL Server中

时间:2015-11-20 16:14:59

标签: sql sql-server case

我要做的是将多个列合并为一个。假设我有一个名为Player的表,此表包含多个列,例如name, team, goalie, left back, right back, center back , left midfield.... and description

description列将包含name + team + left back,因此description将为Ronaldo - Madrid - Forward。当玩家只有一个位置但不能超过一个位置时,我可以填充描述栏吗?

我的SQL:

select 
    name, team, goalie,
    leftback, rightback, centerback,
    left midfield,
    ......,
    name + ' - ' + team + ' - '+ 
    CASE 
       WHEN goalie = 'yes' THEN 'Goalie' 
       WHEN leftback = 'yes' THEN 'Left Back'
       WHEN rightback = 'yes' THEN 'Right Back'
       WHEN centerback = 'yes' THEN 'Center Back'
       .......
    END AS Description
from 
    player

输出:

Ronaldo - Madrid - Forward

如果玩家有多个位置,怎么能让它添加多个位置?

由于

2 个答案:

答案 0 :(得分:5)

select 
   name,
   team, 
   CASE WHEN goalie = 'yes'      THEN 'Goalie - '      ELSE '' END + 
   CASE WHEN leftback = 'yes'    THEN 'LeftBack - '    ELSE '' END + 
   CASE WHEN rightback = 'yes'   THEN 'RightBack - '   ELSE '' END + 
   CASE WHEN center back = 'yes' THEN 'Center Back - ' ELSE '' END AS Description

您必须删除描述中的最后一个-

SQL Server +2012版本

WITH cte as (
   SELECT
      name,
      team, 
      IIF(goalie = 'yes',      'Goalie - ', '') + 
      IIF(leftback = 'yes',    'LeftBack - ', '') + 
      IIF(rightback = 'yes',   'RightBack - ', '') + 
      IIF(center back = 'yes', 'Center Back - ', '') AS Description
   FROM Players
)
SELECT name,
       team,
       CASE LEN(Description) 
          WHEN 0 THEN Description 
          ELSE LEFT(Description, LEN(Description) - 3)
       END
FROM cte

使用STUFF

检查版本的评论

答案 1 :(得分:1)

我不是CASE陈述的粉丝,我宁愿在可能的情况下避免使用它们。你可以通过以下方式逃脱:

select stuff (
              isnull(replace(replace(goalie,'no',''),'yes',' - Goalie'),'')
            + isnull(replace(replace(leftback,'no',''),'yes',' - Leftback'),'')
            + isnull(replace(replace(rightback,'no',''),'yes',' - Rightback'),'')
              ....
              ,1,3,''
             ) as 'Description'
  from Player

如果goalie之类的唯一值是'yes','no'和NULL。