Skip to content
Advertisement

Using Pivot function In SQL Server

I have the below table

I am using the pivot function to flatten the data

and I am getting the below result

The issue is that it is transposing the data from the bottom up meaning it takes the first record that it finds and makes it the last and I wanted it to be like below

What change should I make to the query?

Update I added the SortOrder Column as was suggested and the table is now shown below.

Advertisement

Answer

This is your subquery:

The order by 1/0 is a very strange construct. It is equivalent to: order by (select null). That is, there is no ordering.

Well, you have a problem. Tables, even temporary tables, represent unordered sets in SQL. If you are depending on some innate ordering of the table for your results, then you are out of luck. SQL doesn’t do that.

You need a column that specifies the ordering — presumably some sort of date column or id.

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