I have a table with just two columns like this
mysql> select * from stuff_table;
+------+-------+
| name | stuff |
+------+-------+
| John | shoes |
| Jim | bag |
| Ely | book |
| Tom | bag |
| Will | shoes |
| Pitt | book |
| Dean | bag |
| Luke | bag |
+------+-------+
and I tried with many solutions I found like
select distinct
max(case when stuff='shoes' then name else name is null) end as shoes,
max(case when stuff='bag' then name else name is null end) as bag,
max(case when stuff='book' then name else name is null end) as book
from stuff_table;
but I just got this
+-------+------+------+
| shoes | bag | book |
+-------+------+------+
| Will | Tom | Pitt |
+-------+------+------+
Instead, I want to get this
+-------+------+------+
| shoes | bag | book |
+-------+------+------+
| John | Jim | Ely |
| Will | Tom | Pitt |
| NULL | Dean | NULL |
| NULL | Luke | NULL |
+-------+------+------+
I have tried with sum(case...) or if(case..) or group by too but it doesn't work. Is there any mysql query to get such that table? Kindly help. Thank you.
You dont need to use else and You have a end outside of max function :
Depending on the version of
mysql
you are using, here's one approach establishing arow_number
per group, then usingconditional aggregation
grouped by that row number:Since you are using an older version of
mysql
, you'll need to useuser-defined variables
to establish the row number. The rest then works the same. Here's an example: