Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transposing rows to columns using self join

I have a table named category with values as below,

CategoryId      | Value |     Flag

1                      25                a
2                      26                a
3                      27                a
1                      28                m
2                      23                m
1                      36                p
2                      33                p

Now I want to transpose the rows present in this table to columns based on the flag, something like

CategoryId      | aValue |     mValue   |     PValue
1                      25                28               36
2                      26                23               33
3                      27                null             null

I am trying to join based on the category id but I am just getting the matched records (inner join) in my resultset even if I use left outer join in my query.

My query:

SELECT 
  A.CategoryId, 
  A.Value AS actual, 
  B.Value AS projected, 
  C.Value AS Manual
FROM ((a AS A left JOIN b AS B ON A.categoryid=B.categoryid) 
  left JOIN c AS C ON A.categoryid=C.categoryid) 
WHERE (((A.flag)="a") and ((B.flag)="p") and ((C.flag) ="m"))

I am getting the proper results if I have the data in 3 different tables.

I just want to check what would be the best way to transpose a rows to column when using self join...

Thanks, Barani

like image 946
Learner Avatar asked Dec 07 '25 06:12

Learner


1 Answers

Try this:

SELECT CategoryId, 
       MIN(SWITCH(YourTable.Flag = 'a',Value)) AS aValue,
       MIN(SWITCH(YourTable.Flag = 'm',Value)) AS mValue,
       MIN(SWITCH(YourTable.Flag = 'p',Value)) AS pValue
FROM YourTable
GROUP BY CategoryId
like image 87
Lamak Avatar answered Dec 08 '25 20:12

Lamak



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!