首页 > 解决方案 > 在 SQL Server 中将值转换为列

问题描述

我有这个专栏:

floor
---------
dep:first
dep:second
dep:third
dep:fourth

我想让它像这样:

DEP
------
first
second
third
fourth

我正在尝试这个:

select
    max(case when floor = 'dep:first' then 'first' end) DEP,
    max(case when floor = 'dep:second' then 'second' end) DEP,
    max(case when floor = 'dep:third' then 'third' end) DEP,
    max(case when floor = 'dep:fourth' then 'fourth' end) DEP,
from 
    db.table

但结果返回 DEP 列 4 次:

DEP    |DEP    |DEP     |DEP    |
-------|-------|--------|-------|
first  |second |third   |fourth |

标签: sqlsql-server

解决方案


使用replace()orstuff()怎么样?

select replace(floor, 'dep:', '')

或者:

select stuff(floor, 1, 4, '')

推荐阅读