2

I am working with a SQL problem where I have a variable number of rows with corresponding values that I need to put into columns.

Input table:

id | value
----------
1  | a
1  | b
2  | c
3  | d
3  | e
3  | f

Expected output table:


id | value1 | value2 | value3 | value4 
--------------------------------------
1  | a      | b      | null   | null 
2  | c      | null   | null   | null 
3  | d      | e      | f      | null 

Side notes: The value column is the primary key of the input table. The maximum number of output columns should be fixed to 4.

jarlh
  • 42,561
  • 8
  • 45
  • 63
legalruby
  • 23
  • 2

1 Answers1

1

You can use SQL Pivot technique for this. Try this query.

SELECT *
FROM   (SELECT *, Row_number() OVER (partition BY id ORDER BY id) AS rn
        FROM   Input) src
       PIVOT ( Max([value])
             FOR rn IN ([1],[2],[3],[4]) ) piv;  

Result

+----+---+------+------+------+
| id | 1 |  2   |  3   |  4   |
+----+---+------+------+------+
|  1 | a | b    | NULL | NULL |
|  2 | c | NULL | NULL | NULL |
|  3 | d | e    | f    | NULL |
+----+---+------+------+------+

Table Schema and Data

CREATE TABLE Input
  (
     id    INT,
     [value] NVARCHAR(10)
  );

INSERT INTO Input
VALUES      (1, 'a'),
            (1, 'b'),
            (2, 'c'),
            (3, 'd'),
            (3, 'e'),
            (3, 'f');  
DxTx
  • 3,049
  • 3
  • 23
  • 34