I have a table Machine_Mode_Duration:
I need a query so that it will be displayed as follows:
Suggestions are appreciated!
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With