SQL将列转换为行

时间:2018-01-18 17:55:09

标签: sql sql-server pivot unpivot

[从列到行的SQL Pivot]

current data structure

Image data sample

Hello Folks, 我试图将表中的列转换为Row以满足要求,我能够将多个列值引入一列,但不知道如何转置到行。 感谢您的帮助

WITH mn_result AS(
SELECT 
eh.[RUN_NUMBER], ed.[NOTCH_STEP], ed.[POINT_TYPE], ed.[TESTDATA_ID]
FROM [dbo].[Header] eh 
JOIN
[dbo].[TestData] ed ON eh.[RUN_NUMBER] = ed.[RUN_NUMBER] 

WHERE eh.[RUN_NUMBER] = '01007230')

SELECT [RUN_NUMBER]
,col+value as col,value FROM (
SELECT  [RUN_NUMBER],[NOTCH_STEP] as notch,[POINT_TYPE] as ptype
,[TESTDATA_ID] as id FROM mn_result 
GROUP BY [RUN_NUMBER],[NOTCH_STEP],[POINT_TYPE],[TESTDATA_ID]) rt
unpivot ( value FOR col in (notch,ptype))unpiv
ORDER BY col

1 个答案:

答案 0 :(得分:0)

PIVOTCROSS JOINCROSS APPLY一起考虑,其中SELECT个语句从 ENGINETESTDATA_ID 列移出:

WITH mn_result AS (
   SELECT eh.ENGINETESTDATA_ID, eh.[RUN_NUMBER], ed.[NOTCH_STEP], 
          ed.[POINT_TYPE], ed.[TESTDATA_ID]
   FROM [dbo].[Header] eh 
   JOIN [dbo].[TestData] ed ON eh.[RUN_NUMBER] = ed.[RUN_NUMBER] 
   WHERE eh.[RUN_NUMBER] = '01007230'
)

SELECT s1.*, s2.*
FROM
(
SELECT t.[118427] As [Notch1], 
       t.[118428] As [Notch2], 
       t.[118429] As [Notch3], 
       t.[118430] As [Notch4], 
       t.[118431] As [Notch5], 
       t.[118432] As [Notch6], 
       t.[118433] As [Notch7]

FROM (SELECT ENGINETESTDATA_ID, NOTCH_STEP FROM mn_result) r

PIVOT 
  (
    MAX(r.[NOTCH_STEP]) 
    FOR r.ENGINETESTDATA_ID IN ([118427], [118428], [118429], [118430], 
                                [118431], [118432], [118432])
  ) AS t
) s1

CROSS APPLY
(
SELECT t.[118427] As [Ptype1], 
       t.[118428] As [Ptype2], 
       t.[118429] As [Ptype3], 
       t.[118430] As [Ptype4], 
       t.[118431] As [Ptype5], 
       t.[118432] As [Ptype6], 
       t.[118433] As [Ptype7]

FROM (SELECT ENGINETESTDATA_ID, POINT_TYPE FROM mn_result) r

PIVOT 
  (
    MAX(r.[POINT_TYPE]) 
    FOR r.ENGINETESTDATA_ID IN ([118427], [118428], [118429], [118430], 
                                [118431], [118432], [118433])
  ) AS t
) s2

Rextester Demo