Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query to change vertical to horizontal

I have a table Machine_Mode_Duration:

enter image description here

I need a query so that it will be displayed as follows:

enter image description here

Suggestions are appreciated!

like image 533
Sadiq Avatar asked Apr 11 '14 09:04

Sadiq


People also ask

How do I change data from horizontal to vertical in SQL?

Right-click and select the Paste Special option. 4. Select Transpose in the popup menu. Then the horizontal data will immediately be converted to vertical.

Can you transpose a table in SQL?

In order to transpose a table in SQL, you have to create each new column in your SELECT statement and specify which values you want in each.

How do I rotate a column to a row in SQL?

In SQL Server you can use the PIVOT function to transform the data from rows to columns: select Firstname, Amount, PostalCode, LastName, AccountNumber from ( select value, columnname from yourtable ) d pivot ( max(value) for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber) ) piv; See Demo.


1 Answers

You need a GROUP BY.

Assuming that you have exactly 3 modes and that in case of duplicate (Machine_id, INTERNAL_MODES) tuples it is okay to sum up their INTERNAL_MODE_DURATION:

SELECT
    Machine_Id,
    SUM(CASE WHEN INTERNAL_MODES = 1 THEN INTERNAL_MODE_DURATION ELSE 0 END) AS Mode_1,
    SUM(CASE WHEN INTERNAL_MODES = 2 THEN INTERNAL_MODE_DURATION ELSE 0 END) AS Mode_2,
    SUM(CASE WHEN INTERNAL_MODES = 3 THEN INTERNAL_MODE_DURATION ELSE 0 END) AS Mode_3
FROM t
GROUP BY
    Machine_Id;
like image 165
Daniel Sparing Avatar answered Sep 26 '22 02:09

Daniel Sparing