T-SQL查询转换表

时间:2017-01-18 12:24:30

标签: sql-server pivot

我需要弄清楚,SQL Server中的查询转换表如下图所示。

TABLE PICTURE

1 个答案:

答案 0 :(得分:1)

这可能就是你要找的东西:

DECLARE @t TABLE(Col1 char(1)
                ,Col2 char(1)
                ,Col3 char(1)
                ,ColKey varchar(3)
                ,ColVal1 varchar(2)
                ,ColVal2 varchar(3)
                );

INSERT INTO @t VALUES('A','B','C','EOP','X1','X2')
                    ,('A','B','C','AVG','X3','X4')
                    ,('A','B','C','PL','X5','X6')
                    ,('A','B','E','EOP','X7','X8')
                    ,('A','B','E','PL','X9','X10');


WITH cte_val1 AS(
SELECT Col1, Col2, Col3, [EOP] [EOP Val1], [AVG] [AVG Val1], [PL] [PL Val1]
  FROM
  (
    SELECT Col1, Col2, Col3, ColKey, ColVal1
      FROM @t
  ) src
  PIVOT(
    MIN(ColVal1) FOR ColKey IN ([EOP], [AVG], [PL])
  ) piv
),
cte_val2 AS(
SELECT Col1, Col2, Col3, [EOP] [EOP Val2], [AVG] [AVG Val2], [PL] [PL Val2]
  FROM
  (
    SELECT Col1, Col2, Col3, ColKey, ColVal2
      FROM @t
  ) src
  PIVOT(
    MIN(ColVal2) FOR ColKey IN ([EOP], [AVG], [PL])
  ) piv
)
SELECT cv1.Col1, cv1.Col2, cv1.Col3
      ,cv1.[EOP Val1], cv2.[EOP Val2]
      ,cv1.[AVG Val1], cv2.[AVG Val2]
      ,cv1.[PL Val1], cv2.[PL Val2]
  FROM cte_val1 cv1
  JOIN cte_val2 cv2
    ON cv1.Col1 = cv2.Col1
    AND cv2.Col2 = cv1.Col2
    AND cv2.Col3 = cv1.Col3