Du angav inte RDBMS, men detta är i grunden en pivot
om din databas har tillgång till den funktionen. Om inte, kan du replikera med ett case
och en aggregerad funktion.
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
I SQL Server och Oracle är PIVOT
funktion finns:
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
Du kan skapa dynamiska versioner om du har ett okänt antal belopp som du vill omvandla till kolumner.
Redigera, du uppgav att du använder Oracle, så oraclespecifika svar finns nedan:
Oracle 11g har pivot
funktion:
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
Om du inte använder Oracle 11g måste du använda ett CASE
med aggregatfunktion:
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