Du har ikke specificeret RDBMS, men dette er grundlæggende en pivot
hvis din database har adgang til den funktion. Hvis ikke, kan du replikere ved hjælp af en case
og en samlet 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 og Oracle er PIVOT
funktion eksisterer:
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 oprette dynamiske versioner, hvis du har et ukendt antal beløb, som du ønsker at omdanne til kolonner.
Rediger, du har angivet, at du bruger Oracle, så oracle-specifikke svar er nedenfor:
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
Hvis du ikke er på Oracle 11g, skal du bruge en CASE
med aggregeret funktion:
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