Search code examples
sqlsql-serversubquerypivot-tabletranspose

Convert table rows into columns in Microsoft SQL Server


This is my table :

ID Parameter Reading
1213 Sr No. 1
1213 Sr No. (null)
1213 Sr No. (null)
1213 Name (null)
1213 Name Final Rating
1213 Name Majority Rating
1214 Sr No. 1
1214 Sr No. (null)
1214 Sr No. (null)
1214 Name (null)
1214 Name Final Rating
1214 Name Majority Rating

I want output as:

ID Sr No. Name
1213 1 (null)
1213 (null) Final Rating
1213 (null) Majority Rating

I want to do this in Microsoft SQL Server.

I have written the following query:

SELECT
    (SELECT Reading FROM test_table 
     WHERE ID = 1213 AND Parameter = 'Sr No.') AS SrNo,
    (SELECT Reading FROM test_table 
     WHERE ID = 1213 AND Parameter = 'Name') AS Name
FROM 
    test_table

But I'm getting this error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.


Solution

  • your data

    CREATE TABLE mytable(
       ID        INTEGER  NOT NULL
      ,Parameter VARCHAR(70) NOT NULL
      ,Reading   VARCHAR(70) NOT NULL
    );
    INSERT INTO mytable
    (ID,Parameter,Reading) VALUES 
    (1213,'Sr No.','1'),
    (1213,'Sr No.','(null)'),
    (1213,'Sr No.','(null)'),
    (1213,'Name','(null)'),
    (1213,'Name','Final Rating'),
    (1213,'Name','Majority Rating'),
    (1214,'Sr No.','1'),
    (1214,'Sr No.','(null)'),
    (1214,'Sr No.','(null)'),
    (1214,'Name','(null)'),
    (1214,'Name','Final Rating'),
    (1214,'Name','Majority Rating');
    

    use Row_number and Join in your Subquery to get your desired result

    SELECT A.id,
           [sr no.],
           [name]
    FROM   (SELECT id,
                   reading         AS 'Sr No.',
                   Row_number()
                     OVER(
                       ORDER BY (SELECT NULL)) RN
            FROM   mytable
            WHERE  parameter = 'Sr No.') A,
           (SELECT id,
                   reading         AS 'Name',
                   Row_number()
                     OVER(
                       ORDER BY (SELECT NULL)) RN
            FROM   mytable
            WHERE  parameter = 'Name') B
    WHERE  A.id = B.id
           AND A.rn = B.rn
           AND A.id = 1213    
    

    dbfiddle