Creating a pivot like report in SQL Server [duplicate]

p4rjhz4m  于 2023-04-19  发布在  SQL Server
关注(0)|答案(1)|浏览(116)

This question already has answers here:

Convert Rows to columns using 'Pivot' in SQL Server (9 answers)
Closed 2 days ago.

I have a table with values like the table below:

IDName
1N1
2N2
3N1
4N1
5N3
6N2

And I want to create a report that looks like this:

NameID1ID2ID3
N1134
N226-
N35--

There are two obstacles with this problem, first, the number of IDs for the same name is not fixed and, second column names for IDs should be generated.

I have managed to write a query that generates this report and then by using Dynamic Query, I think I can create the report.

select * from(
select T1.Name,T1.ID as ID1,T2.ID as ID2,T3.ID as ID3, ROW_NUMBER() over (PARTITION BY T1.Name ORDER BY T1.ID) as [Order]
from TestTabel T1 left join TestTabel T2
    on T1.Name=T2.Name and T1.ID<T2.ID left join TestTabel T3
    on T2.Name=T3.Name and T2.ID<T3.ID)T
where T.[Order]=1

But, it seems there should be a better and more straightway solution for it.

Thank you in advance.

cbeh67ev

cbeh67ev1#

Assuming you know the maximum number of IDs per name, you may use a pivot query with the help of ROW_NUMBER :

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY ID) rn
    FROM TestTabel
)

SELECT
    Name,
    MAX(CASE WHEN rn = 1 THEN ID END) AS ID1,
    MAX(CASE WHEN rn = 2 THEN ID END) AS ID2,
    MAX(CASE WHEN rn = 3 THEN ID END) AS ID3,
    MAX(CASE WHEN rn = 4 THEN ID END) AS ID4,
    MAX(CASE WHEN rn = 5 THEN ID END) AS ID5
FROM cte
GROUP BY Name
ORDER BY Name;

相关问题