Tergantung pada versi mysql
yang Anda gunakan, inilah satu pendekatan untuk membuat row_number
per grup, lalu gunakan conditional aggregation
dikelompokkan menurut nomor baris tersebut:
select
rn,
max(case when stuff = 'bag' then name end) 'bag',
max(case when stuff = 'book' then name end) 'book',
max(case when stuff = 'shoes' then name end) 'shoes'
from (
select *, row_number() over (partition by stuff order by name) rn
from stuff_table
) t
group by rn
Karena Anda menggunakan mysql
versi lama , Anda harus menggunakan user-defined variables
untuk menetapkan nomor baris. Sisanya kemudian bekerja sama. Ini contohnya:
select
rn,
max(case when stuff = 'bag' then name end) 'bag',
max(case when stuff = 'book' then name end) 'book',
max(case when stuff = 'shoes' then name end) 'shoes'
from (
select *,
( case stuff
when @curStuff
then @curRow := @curRow + 1
else @curRow := 1 and @curStuff := stuff
end
) + 1 AS rn
from stuff_table, (select @curRow := 0, @curStuff := '') r
order by stuff
) t
group by rn