Anda tidak menentukan RDBMS, tetapi ini pada dasarnya adalah pivot
jika database Anda memiliki akses ke fungsi itu. Jika tidak, Anda dapat mereplikasi menggunakan case
dan fungsi agregat.
MySQL :
select name,
sum(case when group_rn = 1 then amount else 0 end) Amount1,
sum(case when group_rn = 2 then amount else 0 end) Amount2,
sum(case when group_rn = 3 then amount else 0 end) Amount3
from
(
select name,
@num := if(@name = `name`, @num + 1, 1) as group_rn,
@name := `name` as dummy,
amount
from
(
select p.name,
d.amount,
d.decl_id
from person p
inner join declaration d
on p.person_id = d.person_id
) src
order by name
) p
group by name
Lihat SQL Fiddle dengan Demo
Di SQL Server dan Oracle PIVOT
fungsi ada:
SQL Server :
select name,
[1] as Amount1,
[2] as Amount2,
[3] as Amount3
from
(
select p.name,
d.amount,
row_number() over(partition by p.name order by d.amount) rn
from person p
inner join declaration d
on p.person_id = d.person_id
) src
pivot
(
sum(amount)
for rn in ([1], [2], [3])
) p
Lihat SQL Fiddle dengan Demo
Anda dapat membuat versi dinamis, jika Anda memiliki jumlah yang tidak diketahui yang ingin Anda ubah menjadi kolom.
Sunting, Anda menyatakan Anda menggunakan Oracle, jadi jawaban spesifik Oracle ada di bawah:
Oracle 11g memiliki pivot
fungsi:
select name,
Amount1,
Amount2,
Amount3
from
(
select p.name,
d.amount,
row_number() over(partition by p.name order by d.amount) rn
from person p
inner join declaration d
on p.person_id = d.person_id
) src
pivot
(
sum(amount)
for rn in ('1' as Amount1, '2' as Amount2, '3' as Amount3)
) p
Lihat SQL Fiddle dengan Demo
Jika Anda tidak menggunakan Oracle 11g, maka Anda perlu menggunakan CASE
dengan fungsi agregat:
select name,
sum(case when rn = 1 then amount else 0 end) Amount1,
sum(case when rn = 2 then amount else 0 end) Amount2,
sum(case when rn = 3 then amount else 0 end) Amount3
from
(
select p.name,
d.amount,
row_number() over(partition by p.name order by d.amount) rn
from person p
inner join declaration d
on p.person_id = d.person_id
) src
group by name
Lihat SQL Fiddle dengan Demo