如何将一列拆分为不同的列

How can I split a column into different columns

我有包含 3 种类型值的 varchar 列。我想根据值的类型将它分成 3 列。例如我的专栏是, 值的工厂名称

  1. 阿南塔
  2. 阿南塔
  3. ATL
  4. ESBL
  5. ATL
  6. ATL

当 FactoryName 的值为 "ANANTA"、"ATL" & "ESBL" respectively.The 结果应该是

使用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