2012-10-31 65 views
-2

任何人都可以用sql語句幫助我產生以下結果嗎?SQL語句加入並給出多個列的結果

Table Person 
Person_ID Name 
1   John 
2   Paul 

Table Declaration 
Decl_ID    Person_ID Amount 
1     1    10 
2     2    12 
3     1    99 
4     1    24 

結果的SQL statment的應該是這樣的:

Name Amount1 Amount2 Amount3 
John 10  99  24 
Paul 12 
+2

您使用的是哪種rdbms? – Taryn

+1

@ user1788822因此,如果在''John''聲明中有1000000000000000000條記錄,那麼您需要1000000000000000000列? – ppeterka

+1

看起來像一個數據透視表,這是標準的SQL不適合的。當您顯示數據時,這種轉換最好在客戶端完成。 –

回答

2

沒有指定的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

+0

謝謝!不知道有這樣一個樞軸功能。 – user1788822

+0

@ user1788822是的,'oracle'和'sql server'都有'pivot'功能。它適用於這些類型的結果。 'PIVOT'函數只在11g中可用,所以你在那之前,那麼你將需要使用具有聚集函數的'case'。 – Taryn

+0

@ user1788822你將有一個未知數量的數值,你需要轉換成列? – Taryn