Skip to content
Advertisement

Reformatting SQL output

I have data that looks like this

Name  XX YY
alpha 10 77
beta  10 90
alpha 20 72
beta  20 91
alpha 30 75
beta  30 94
alpha 40 76
beta  40 95

If I use

select * from scores order by Name, XX

I will get

Name  XX YY
alpha 10 77
alpha 20 72
alpha 30 75
alpha 40 76
beta  10 90
beta  20 91
beta  30 94
beta  40 95

At the moment, I’m retrieving the data in this form and using some C coding to format it like

Name   xx=10  xx=20  xx=30  xx=40
alpha  77     72     75     76
beta   90     91     94     95

Assuming that there will always be entries for 10, 20, 30, 40 for every name, is something like this possible in SQL without creating a new table like in SQL Reformatting table columns

Advertisement

Answer

You need to use PIVOT to get your desired results. Before using PIVOT, some customization required in your value in column XX so that the final column output can meet your expectation.

SELECT * FROM
(
SELECT Name,'XX='+CAST(XX AS VARCHAR) XX,YY 
FROM your_table
)AS P
PIVOT(
    SUM(YY)
    FOR XX IN ([XX=10],[XX=20],[XX=30],[XX=40])
) PP

Output-

Name    XX=10   XX=20   XX=30   XX=40
alpha   77      72      75      76
beta    90      91      94      95

The same output can be also achieved with this following query-

SELECT Name,
[10] AS [XX=10],
[20] AS [XX=20],
[30] AS [XX=30],
[40] AS [XX=40]
FROM
(
    SELECT Name, XX,YY 
    FROM your_table
)AS P
PIVOT(
    SUM(YY)
    FOR XX IN ([10],[20],[30],[40])
) PP
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement