Skip to content
Advertisement

Without using aggregate function can we do pivot in sql

For above query i’m getting data which is returning only 1 row. The image is attached below enter image description here

But i need multiple rows as a result from the below table enter image description here

I need a output as

Advertisement

Answer

No it is not possible to do PIVOT without an aggregate function, but you can make the aggregate function arbitrary by ensuring there is only one source row per group. It is not immediately clear from your question what your logic is though:

For example, you have two values for a time of 12 (KA108112 and KA106360), and 3 rows for a time of 13 (TN04F6726, TN28C3709, TN52C4788), so there are a few different ways you could combine these two.

You could return the cartesian product:

Or you could return each result once, e.g.

But you also need to provide additional logic, i.e. why would KA106360 match with TN04F6726, rather than any of the other two values (in the above example I have ordererd Trailer_RegNo alphabetically within each time, but there could be any number of ways of doing this.

Based on your comment, it seems like you want to arbitralily pair values, so in order to make sure that every value is represented you need to make each row unique, which you can do using ROW_NUMBER(), e.g.

Which gives:

Now you have a way of pairing your items (i.e. KA106360 & TN04F6726, KA108112 & TN28C3709 etc). To change how items are grouped, you would just need to change the ORDER BY clause in the ROW_NUMBER() funciton.

So your final query might be something like:

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