-4

How to transform Rows into Columns for the below table data in SQL serer

Actual table

LabelID  |  LabelName
---------------------
    1    |  Label1
    2    |  Label2
    3    |  Label3
    4    |  Label4
    5    |  Label5

Expected table

    1  |    2   |   3   |   4    |  5   
------------------------------------------
Label1 | Label2 | Labe3 | Label4 | Label15
Backl
  • 3
  • 1
  • 2
    Does this answer your question? [Convert Rows to columns using 'Pivot' in SQL Server](https://stackoverflow.com/questions/15931607/convert-rows-to-columns-using-pivot-in-sql-server) – Digvijay S Jul 24 '20 at 14:00
  • 1
    Why tag 3 completely different versions of SQL Server, all of which are unsupported, and 2 of them **completely** unsupported. If you are using 2005, then you many of the answer you find it may well not work, as you're using technology that has had no support for 5~ years. – Thom A Jul 24 '20 at 14:02
  • Do you have more rows for 1 or 2 or ...? – mkRabbani Jul 24 '20 at 14:03

1 Answers1

0

Here is a sample query that might help you to achieve your required output. This query will work in case you have that 5 rows in real as well. In case of more rows and variety in data, you need to adjust the query as per your data and required output.

SELECT 
MAX(CASE WHEN LabelID = 1 THEN  LabelName END) [1],
MAX(CASE WHEN LabelID = 2 THEN  LabelName END) [2],
MAX(CASE WHEN LabelID = 3 THEN  LabelName END) [3],
MAX(CASE WHEN LabelID = 4 THEN  LabelName END) [4],
MAX(CASE WHEN LabelID = 5 THEN  LabelName END)[5]
FROM your_table
mkRabbani
  • 16,295
  • 2
  • 15
  • 24