您没有指定 RDBMS,但这基本上是pivot
您的数据库有权访问该功能的情况。如果没有,那么您可以使用 acase
和聚合函数进行复制。
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
请参阅带有演示的 SQL Fiddle
在 SQL Server 和 Oracle 中,该PIVOT
函数存在:
SQL 服务器:
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
请参阅带有演示的 SQL Fiddle
如果您想要转换为列的数量未知,您可以创建动态版本。
编辑,您说您使用的是 Oracle,所以 oracle 的具体答案如下:
Oracle 11g 具有以下pivot
功能:
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
请参阅带有演示的 SQL Fiddle
如果您不在 Oracle 11g 上,则需要使用CASE
with 聚合函数:
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
请参阅带有演示的 SQL Fiddle