我有varchar列有3种类型的值。我想根据值的类型将其拆分为3列。比如我的专栏是, FactoryName of values
当FactoryName的值为" ANANTA"," ATL"时,我想要3个名为Factory1,Factory2,Factory3的列。 &安培; " ESBL"分别。结果应该是
NULL
FACTORY2
ATL
我可以使用案例或其他方式吗?怎么样?
答案 0 :(得分:2)
使用Pivot
转置数据
CREATE TABLE #comp
(
name VARCHAR(50)
)
INSERT #comp
VALUES ('ANANTA'),('ANANTA'),('ATL'),
('ESBL'),('ATL'),('ATL')
SELECT [ANANTA] AS factory1,
[ATL] AS factory2,
[ESBL] AS factory3
FROM #comp
PIVOT (Max(name)
FOR name IN ([ANANTA],
[ATL],
[ESBL])) piv
或conditional Aggregate
select max(case when name = 'ANANTA' then name end) factory1,
max(case when name = 'ATL' then name end) factory2,
max(case when name = 'ESBL' then name end) factory3
from #comp
更新:如果您不想将结果显示为单行,请删除max
汇总
SELECT CASE WHEN name = 'ANANTA' THEN name END factory1,
CASE WHEN name = 'ATL' THEN name END factory2,
CASE WHEN name = 'ESBL' THEN name END factory3
FROM #comp