沒有指定的RDBMS,但是這基本上是一個pivot
,如果你的數據庫訪問該功能。如果不是,那麼您可以使用case
和一個聚合函數進行復制。
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 with Demo
在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 with Demo
您可以創建動態的版本,在事件中,你有一個未知的數字要變成列金額。
編輯,你說你正在使用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 with Demo
如果你不在Oracle 11g上,那麼您將需要使用帶集合函數的CASE
:
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 with Demo
您使用的是哪種rdbms? – Taryn
@ user1788822因此,如果在''John''聲明中有1000000000000000000條記錄,那麼您需要1000000000000000000列? – ppeterka
看起來像一個數據透視表,這是標準的SQL不適合的。當您顯示數據時,這種轉換最好在客戶端完成。 –