TSql Pivot或Rows to Columns

时间:2015-03-29 08:30:45

标签: sql sql-server tsql pivot unpivot

我在Pivot上看过各种帖子或将行转换为列,但我仍然没有运气,所以我决定发布这个问题。

我的表 cols

Id col_name 1 Serial 2 Data1 3 Data2

我的表

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

任何帮助都会有所帮助。

2 个答案:

答案 0 :(得分:1)

我将指出您的数据模型需要一些改进,因此我加入串行的方法是即兴的,并且在实际项目中不可信任,您的表之间没有逻辑连接。以下是如何转动数据:

;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

答案 1 :(得分:0)

我不认为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