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

SQL – Transpose one column of data into a row

I am looking to take the values of a single column and transpose them into the corresponding row for each ClientGUID. A simple example of the of what I have post SELECT statement is:

ClientGUID DxCode
12345 50.8
12345 62.5
12345 42.1

What I am trying to accomplish is this, if possible:

ClientGUID DxCode1 DxCode2 DxCode3
12345 50.8 62.5 42.1

For this example my SELECT statement looks a such:

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

    SELECT ClientGUID, DxCode
    FROM MyTable
    WHERE ClientGUID = 12345

Any thoughts or direction would be greatly appreciated! Thanks!

>Solution :

You can use PIVOT for this, e.g.:

;WITH src AS
(
  SELECT ClientGUID, DxCode,
    rn = ROW_NUMBER() OVER (PARTITION BY ClientGUID ORDER BY @@SPID)
  FROM dbo.ClientDxCodes
  -- WHERE ClientGUID = 12345
)
SELECT ClientGUID, DxCode1 = [1], DxCode2  = [2], DxCode3 = [3],
    DxCode4 = [4], DxCode5 = [5], DxCode6  = [6], DxCode7 = [7],
    DxCode8 = [8], DxCode9 = [9], DxCode10 = [10]
FROM src
PIVOT 
(
  MAX(DxCode) 
  FOR rn IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10])
) AS p;

Output:

ClientGUID DxCode1 DxCode2 DxCode3 DxCode4 DxCode5 DxCode6 DxCode7 DxCode8 DxCode9 DxCode10
12345 50.8 62.5 42.1 null null null null null null null
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