0

I am trying to transpose (Pivot?) a table. This is my current setup.
Current Table:

ID | Value
1  | 10
1  | 11
1  | 12
1  | 13
1  | 14
2  | 123
3  | 13423
3  | 1134
3  | 1234

Seeking the following result:

ID | Value01 | Value 02 | Value 03 | Value 04 | Value 05
1  |  10     |  11      |   12     |   13     |  14
2  |  123
3  | 13423   | 1134     | 1234

Currently I am trying it with PIVOT however I am not completely sure how to PIVOT without a "category column" (such as days, or months). Could I use the ID column for this?

SELECT ID, Value, [0], [1], [2], [3], [4] 
FROM (
      SELECT ID, Value FROM dbo.TABLE
) SourceTable 
PIVOT (
      VALUE FOR ID IN ([0], [1], [2], [3], [4])
) AS PivotTable

There is no preset amount of VALUE's for each ID. But if it is required to have a known number, 5 values (and thus 5 columns) is enough.

4

1 回答 1

3

您当前的查询已关闭,您缺少想要作为新列名的值。我的建议是使用row_number()which 将在 each 上创建一个递增的值id,然后您可以使用 PIVOT 函数为max(value)这些序列值中的每一个返回 :

SELECT ID, [0], [1], [2], [3], [4] 
FROM 
(
  SELECT ID, Value, 
    row_number() over(partition by id 
                        order by id) -1  seq
  FROM yourtable
) SourceTable 
PIVOT 
(
  max(VALUE)
  FOR seq IN ([0], [1], [2], [3], [4])
) AS PivotTable;

请参阅带有演示的 SQL Fiddle

于 2013-07-29T18:29:33.313 回答