Vinayak Agrawal
Vinayak Agrawal

Reputation: 128

How To pivot a table without the pivot function?

I need to pivot a table, make the row values into columns but the catch is that I dont have pivot functionality to call. I need to find a workaround to get this done.

Example:

NAME   SUBJECT     MARKS
Adam    maths        88
Adam    Science      76
Matt    Science      87
joe     English      90 
joe     Maths        80 
joe     Science      40  

Needs to look like : 

NAME     SCIENCE   MATHS    ENGLISH   
Adam        76      88        null
Matt        87      null      null
Joe         40      80        90

and I dont have pivot function available.

Upvotes: 0

Views: 121

Answers (1)

dotjoe
dotjoe

Reputation: 26940

In the absence of pivot you can get the same results with case statements inside your aggregate function...

select
    name,
    science = sum(case when subject = 'science' then marks else null end)
    maths = sum(case when subject = 'maths' then marks else null end)
from
    table
group by
    name

Upvotes: 3

Related Questions