Search code examples
sqlsql-servert-sqlsql-server-2012pivot

Pivoting the table rows to colums


My table is as follows:

declare @tab TABLE (Id int, Rid INT, FValue VARCHAR(50), FText VARCHAR(50))

INSERT INTO @tab VALUES
   (1,1,'Patient','P1'),
   (1,1,'Sdate','01/06/2023'),
   (1,1,'Acc#','123265'),
   (1,1,'Status','New'),
   (1,2,'Patient','P2'),
   (1,2,'Sdate','02/06/2023'),
   (1,2,'Acc#','512364'),
   (1,2,'Status','New'),
   (1,3,'Patient','P3'),
   (1,3,'Sdate','03/06/2023'),
   (1,3,'Acc#','632154'),
   (1,3,'Status','Complete')

select * from @tab

I tried pivoting it, using the following code, but without any success.

select RNo, Patient, Sdate, Acc#,[Status]
from
(
  select Rid, FValue, FText
  from @tab
) d
pivot
(
  max(Rid) for FText in (Rno, Patient, Sdate, Acc#,[Status])
) piv;

Output table should be:

declare @tab1 TABLE (Rno int, Patient VARCHAR(50), Sdate Datetime, Acc# VARCHAR(50), [Status] VARCHAR(50))

INSERT INTO @tab1 
VALUES
   (1,'P1','01/06/2023','123265','New'), 
   (2,'P2','02/06/2023','512364','New'), 
   (3,'P3','03/06/2023','632154','Complete')

select * from @tab1

Solution

  • It's a simple PIVOT, which turns the unique values from the FValue column into multiple columns:

    SELECT *
    FROM (
       SELECT Id, Rid, FValue, FText
       FROM @tab
    ) t
    PIVOT (
       MAX(FText) FOR FValue IN ([Patient], [Sdate], [Acc#], [Status])
    ) p