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 group data based on a column and pivot rows to (unknown) columns

I’m trying to pivot a synonyms table into an unknown number of columns (T-SQL). I’m using SQL Server 2017.

I have this table:

  fd_Id |  fd_Word  |   fd_Interpretation
---------------------------------------------
    1   |   smile   |          1
    2   |   grin    |          1
    3   |   laugh   |          1
    4   |   see     |          2
    5   |   detect  |          2
    6   |   look    |          2
    7   |   peek    |          2
    8   |   walk    |          3
    9   |   stroll  |          3

fd_Id is an identity column and synonyms are grouped by fd_Interpretation. While synonyms can have any number of rows (10+), in practice they are around 6 to 8.

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

This is the desired output:

   Id   |   Word1   |   Word2   |   Word3   |   Word4   |   Wordn...
---------------------------------------------------------------------
   1    |   grin    |   laugh   |   smile   |           |
   2    |   detect  |   look    |   peek    |   see     |
   3    |   stroll  |   walk    |           |           |

Id is a ROW_NUMBER or RANK. Optional if too much trouble.

I looked at other similar PIVOT row questions here but couldn’t find one that is close enough.

Any help is highly appreciated.

>Solution :

A straight-up PIVOT in concert row_number() with should do the trick

Select *
 From (
        Select ID = fd_Interpretation
              ,Item = concat('Word',row_number() over (partition by fd_Interpretation order by fd_Word) )
              ,Value = fd_Word
         From  YourTable
      ) src
 Pivot ( max( Value ) for Item in ([Word1],[Word2],[Word3],[Word4],[Word5],[Word6],[Word7],[Word8]) ) pvt
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