Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert table to key value pair

I’m looking to flatten my current table. At the moment I was able to achieve this through an iterative approach but the run time is very poor. I queried the table and then used a cursor to iterate and insert into a new table.

My current table has many many columns and I’m trying to have it flattened. Possibly unpivot.

RecordId    FirstName    LastName    Country     Grade
1           Joe          Fresh       Canada      95
2           John         Smith       Canada      94

The new table would look like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

RecordId    Key        Value
1           FirstName   Joe
1           LastName    Fresh
1           Country     Canada
1           Grade       95
2           FirstName   John
2           LastName    Smith
2           Country     Canada
2           Grade       94

May I have some guidance.

I tried unpivot and was able to flatten the table but I’m missing RecordId column

select [Key], [Value]
from
(
  SELECT * 
  FROM test
) src
unpivot
(
  [Value] for [Key] in ([RecordId],[FirstName],[LastName], [Country], [Grade])
)

>Solution :

Yes, it is unpivoting. Please include the RecordId column in the unpivoted result by adding it to the SELECT statement before the UNPIVOT operation. Try this:

SELECT RecordId, [Key], [Value]
FROM
(
  SELECT RecordId, FirstName, LastName, Country, Grade
  FROM test
) src
UNPIVOT
(
  [Value] FOR [Key] IN (FirstName, LastName, Country, Grade)
) unpvt;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading