Skip to content
Advertisement

How to select a specific number of rows and convert them into named columns

I am hanging on this problem for hours.

A very simple query:

SQL Result:

RoomId WaterMeterNumber
95E5ACE0-FEE4-4D33-BC22-0DCF7B1155CF SZ12800491
95E5ACE0-FEE4-4D33-BC22-0DCF7B1155CF 3375791
95E5ACE0-FEE4-4D33-BC22-0DCF7B1155CF 45332
95E5ACE0-FEE4-4D33-BC22-0DCF7B1155CF SK9649

And I want the query result to be like that:

RoomId Number1 Number2 Number3 Number4 Number5
95E5ACE0-FEE4-4D33-BC22-0DCF7B1155CF SZ12800491 3375791 45332 SK9649

I always want to show the numbers of the first five watermeters of a room. So the columns need to have a static name.

I already tried combining five windowing functions in mssql but the problem is that I can not dynamically set the room ID inside the window query.

This query would work but how I said the RoomId needs to be dynamic.

I want it that way, so I can use it in another main query.

Is there a way to achieve this with a pivot function or smth like that?

Thank you in advance.

Advertisement

Answer

You can use conditional aggregation:

If you want this for only one RoomId, then add:

to the subquery.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement