透视SQL Server中的列

时间:2014-08-11 14:16:39

标签: sql sql-server sql-server-2000

我有一个SQL Server表,其结构如第1张图所示。必须如第2张图所示显示。如何在SQL Server 2000中实现这一点?

enter image description here

1 个答案:

答案 0 :(得分:0)

鉴于所有记录(_A1,_A2)的相同模式,以下内容适用于您:添加额外的列和/或根据需要取出不必要的列。

SELECT 
  LEFT(measure, CHARINDEX('_', measure)-1) AS Measure,
  LEFT(measure, CHARINDEX('_', measure)-1) + '_A1' AS Measure_A1, --Not sure you need this
  SUM(CASE WHEN RIGHT(measure,2) = 'A1' THEN YTD ELSE 0 END) AS YTD_A1,
  SUM(CASE WHEN RIGHT(measure,2) = 'A1' THEN Q1 ELSE 0 END) AS Q1_A1,
  SUM(CASE WHEN RIGHT(measure,2) = 'A1' THEN Q2 ELSE 0 END) AS Q2_A1,
  LEFT(measure, CHARINDEX('_', measure)-1) + '_A2' AS Measure_A2, --Not sure you need this
  SUM(CASE WHEN RIGHT(measure,2) = 'A2' THEN YTD ELSE 0 END) AS YTD_A2,
  SUM(CASE WHEN RIGHT(measure,2) = 'A2' THEN Q1 ELSE 0 END) AS Q1_A2,
  SUM(CASE WHEN RIGHT(measure,2) = 'A2' THEN Q2 ELSE 0 END) AS Q2_A2
FROM Structure
GROUP BY LEFT(measure, CHARINDEX('_', measure)-1)

SQL Fiddle