Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert data from multiple columns into single row sorting descending

Tags:

sql

I am trying to query the original source which contain totals from a category (in this case Vehicles) into the second table.

Motorcycle Bicycle Car
1 3 2

Desired Output:

Vehicle Quantity
Bicycle 3
Car 2
Motorcycle 1

Additionally, I need that the Quantity is sorted in descending order like showing above.

So far I have tried to do an Unpivot, but there is a syntax error in the Unpivot function. Is there another way to reach out the same results?

My code so far:

SELECT Vehicle_Name 
FROM 
( 
SELECT [Motorcycle], [Bycycle], [Car] from Data
) as Source  
UNPIVOT 
( 
Vehicle FOR Vehicle_Name IN ([Motorcycle], [Bycycle], [Car])
) as Unpvt
like image 478
newbie_coder Avatar asked Jan 26 '26 11:01

newbie_coder


1 Answers

Edit: Added sort requirement.

You can use CROSS APPLY here too

select vehicle, amnt
from test
cross apply( 
 VALUES('motorcycle', motorcycle)
   ,('bicycle', bicycle)
   ,('car', car)) x (vehicle, amnt)
order by amnt desc 

Fiddle here

like image 186
Edward Radcliffe Avatar answered Jan 28 '26 02:01

Edward Radcliffe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!