Skip to content
Advertisement

How to Merge Identical Rows with different column?

I have a table like this:

--------------------------------------------
| Job | Class | Employee | PayType | Hours |
| 212     A      John         1        20  |
| 212     A      John         2        10  |
| 911     C      Rebekah      1        15  |
| 911     C      Rebekah      2        10  |
--------------------------------------------

I want to convert this table so i can get following output

------------------------------------
| Job | Class | Employee | OT | ST |
| 212 |   A   | John     | 20 | 10 |
| 911 |   C   | Rebekah  | 15 | 10 |
------------------------------------

Here I’ve set 1 for OT and 2 for ST

Advertisement

Answer

You can conditional aggregation:

select 
    job,
    class,
    employee
    sum(case when paytype = 1 then hours else 0 end) ot,
    sum(case when paytype = 2 then hours else 0 end) st
from mytable
group by
    jobs,
    class,
    employee
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement