如何将列拆分为不同的列

时间:2015-02-03 06:07:06

标签: sql database sql-server-2012

我有varchar列有3种类型的值。我想根据值的类型将其拆分为3列。比如我的专栏是,     FactoryName of values

  1. 阿南塔
  2. 阿南塔
  3. ATL
  4. ESBL
  5. ATL
  6. ATL
  7. 当FactoryName的值为" ANANTA"," ATL"时,我想要3个名为Factory1,Factory2,Factory3的列。 &安培; " ESBL"分别。结果应该是

    • FACTORY1
    • 阿南塔
    • 阿南塔
    • NULL
    • NULL
    • NULL
    • NULL

    • FACTORY2

    • NULL
    • NULL
    • ATL
    • NULL
    • ATL
    • ATL

      我可以使用案例或其他方式吗?怎么样?

1 个答案:

答案 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