TSql 数据透视表或行到列

TSql Pivot or Rows to Columns

我在 Pivot 上看到了各种 post 或将行转换为列,但我仍然没有运气,所以我决定 post 这个问题。

我的table

Id col_name 1 Serial 2 Data1 3 Data2

我的table

Id col_id value 1 1 1 2 1 2 3 1 3 4 2 25 5 2 26 6 2 27 7 3 28 8 3 29 9 3 30

我想要如下结果,我认为使用 unpivot 或 pivot 可能有效。结果应该是 -

Serial Data1 Data2 1 25 28 2 26 29 3 27 30

任何帮助都会有所帮助。

我认为 pivot 在这里没有用。试试这个

WITH cte1
     AS (SELECT Row_number()OVER(ORDER BY Id) RN,
                value            AS Data1
         FROM   yourtable
         WHERE  col_id = 1),
     cte2
     AS (SELECT Row_number()OVER(ORDER BY Id) RN,
                value            AS Data2
         FROM   yourtable
         WHERE  col_id = 2),
     cte3
     AS (SELECT Row_number()OVER(ORDER BY Id) RN,
                value            AS Data3
         FROM   yourtable
         WHERE  col_id = 3)
SELECT Row_number()OVER(ORDER BY a.rn) AS serial,
       Data1,
       Data2,
       Data3
FROM   cte1 A
       FULL OUTER JOIN cte2 B
                    ON a.RN = b.RN
       FULL OUTER JOIN cte3 C
                    ON b.RN = C.RN 

我要指出你的数据模型需要一些改进,所以我加入串行的方法是即兴的,在现实生活中不能被信任,你的表之间没有逻辑连接。以下是数据透视的方法:

;WITH [rows] AS
(
  SELECT id, value, col_id
  FROM 
    (values
    (1,1,1),(2,1,2),
    (3,1,3),(4,2,25),
    (5,2,26),(6,2,27),
    (7,3,28),(8,3,29),
    (9,3,30)) x(Id, col_id, value)
), cols as
(
  SELECT cols.id, col_name
  FROM
    (values
      ( 2, 'Data1'),( 3, 'Data2')) 
      cols(Id, col_name)
), result as
(
  SELECT row_number() OVER (partition by col_id order by [rows].id) rn, col_name, value
  FROM
    cols
  JOIN
    [rows]
  ON [rows].col_id = cols.id
  WHERE cols.id > 1
)
SELECT rn Serial, Data1, Data2
FROM
  result
PIVOT
(min([value])  
FOR col_name
in([Data1],[Data2])  
)AS p

结果:

Serial Data1 Data2
1      25    28
2      26    29
3      27    30