SQL Pivot用于多列

时间:2015-12-11 17:32:23

标签: sql sql-server pivot

我有下表' EmpTemp':

Name | Category | Value1 | Value 2
John | Cat1     |  11    |   33
John | Cat2     |  22    |   44

我想为表格提供以下输出:

Name | Cat1_Value1 | Cat2_Value1 | Cat1_Value2 | Cat2_Value2
John |      11     |      11     |      33     |     44

我想这给出了我期待的转型的基本概念。我尝试了以下查询,为我提供了部分解决方案:

SELECT 
    Name, 
    Cat1 AS 'Cat1_Value1', 
    Cat2 AS 'Cat2_Value1', 
FROM EmpTemp AS T
PIVOT
(
    MAX(Value1)
    FOR Category IN (Cat1, Cat2)
) AS PVT

以上查询给出了以下结果:

Name | Cat1_Value1 | Cat2_Value1
John |      11     |      11    

我被困住了如何扩展此数据透视查询。提前感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

以下是使用Pivot进行此操作的方法。

首先,您需要unpivot数据然后执行pivot

;with cte as
(
select name,val,col_name from yourtable 
cross apply (values 
            (value1,Category+'value1'),
            (value2,Category+'value2')
            ) cs(val,col_name)
  )
  select * from cte
  pivot(max(val) for col_name in([Cat1value1],
                                 [Cat1value2],
                                 [Cat2value1],
                                 [Cat2value2]
                                )) p

答案 1 :(得分:0)

这是一种不使用pivot语法的简单方法:

select name,
       max(case when category = 'Cat1' then value1 end) as cat1_value1,
       max(case when category = 'Cat2' then value1 end) as cat2_value1,
       max(case when category = 'Cat1' then value2 end) as cat1_value2,
       max(case when category = 'Cat2' then value2 end) as cat2_value2
  from EmpTemp
 group by name