SQL将多个列合并为一列

时间:2013-12-12 21:39:23

标签: sql sql-server

我有一个结合两个表的SQL语句,但最近我被要求添加案例条件。条件正在起作用,但我遇到的问题是每个条件都会创建一个重复的列。

case when s.Department = 'Aero' then '(OA)' else '' end as Blah,
case when s.Department = 'Terrent' then '(OT)' else '' end as Blah,
case when s.Department = 'Vertigo' then '(OMG)' else '' end as Blah

This causes me to end up with

a| b | c | d | Blah | Blah | Blah|
 |   |   |   | (OT) | (OA) | (OT)|
 |   |   |   | (OT) |      |     |
 |   |   |   | (OT) | (OA) |     |
 |   |   |   | (OT) | (OA) | (OT)|
 |   |   |   |      |      | (OT)|

如何使用“case”cmd并将所有结果显示在1列以下?

a| b | c | d | Blah |
 |   |   |   | (OT) |
 |   |   |   | (OT) |
 |   |   |   | (OT) |
 |   |   |   | (OT) |
 |   |   |   | (OA) |
 |   |   |   | (OA) |
 |   |   |   | (OA) |
 |   |   |   | (OT) |
 |   |   |   | (OT) |
 |   |   |   | (OT) |

1 个答案:

答案 0 :(得分:1)

您将使用一个案例陈述而不是三个:

 (case when s.Department = 'Aero' then '(OA)' 
      when s.Department = 'Terrent' then '(OT)' 
      when s.Department = 'Vertigo' then '(OMG)'
      else ''
  end) as Blah