Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL table data horizontally using PIVOT

My SQL table is


  GUID               Step_ID        Value
----------------------------------------------
ADFE12-ASDER-...      1             10
ADFE12-ASDER-...      2             20
ADFE12-ASDER-...      3             30
ADFE12-ASDER-...      4             160
CD4563-FG567-...      1             20
CD4563-FG567-...      2             80
Q23RT5-GH678...       1             30
Q23RT5-GH678-...      2             80
Q23RT5-GH678-...      3             20

And Expected result should be


GUID                  1        2        3        4
---------------------------------------------------
ADFE12-ASDER-...      10       20       30       160
CD4563-FG567-...      20       80      NULL     NULL
Q23RT5-GH678-...      30       80      20       NULL

Here I need to get the details on the basis of column whose data type is GUID. I tried using PIVOT table but getting an exception because I cannot use an aggregate function on GUID column. Is there any other alternative or approach I can use to get the above desired result.

like image 593
Girish Mahida Avatar asked Jun 30 '26 00:06

Girish Mahida


1 Answers

Try this:

select [GUID],[1],[2],[3],[4]
from
(
  select [GUID], Step_ID, Value
  from test
) d
pivot
(
  max(Value)
  for Step_ID in ([1],[2],[3],[4])
) piv;

SQL FIDDLE DEMO

like image 113
Rahul Tripathi Avatar answered Jul 02 '26 14:07

Rahul Tripathi



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!