2013-07-27 70 views
0

我需要你的幫助。如何從一行中選擇多行輸出的數據(posgresql)

我有數據在這樣

customer_no | name | chance 
--------------------------- 
00000000001 | AAAA |  3 
00000000002 | BBBB |  2 
00000000003 | CCCC |  1 

臺試驗現在,我想從多個輸出臺試驗選擇通過現場的機會

輸出這樣

customer_no | name 
------------------ 
00000000001 | AAAA 
00000000001 | AAAA 
00000000001 | AAAA 
00000000002 | BBBB 
00000000002 | BBBB 
00000000003 | CCCC 
的價值計算

如何在pgsql數據庫中選擇命令?任何人都請幫助我。

謝謝。

,阿土伯

回答

1
with recursive CTE_nums as (
    select max(chance) as num from test 
    union all 
    select num - 1 from CTE_nums 
    where num > 1 
) 
select 
    t.customer_no, t.name 
from test as t 
    inner join CTE_nums as n on n.num <= t.chance 
order by 1, 2 

SQL FIDDLE EXAMPLE

4

試試這個:

SELECT customer_no, name FROM (
    SELECT test.*, 
      generate_series(1,chance) i 
    FROM test 
) test; 

這裏是一個demo

+0

[您清除的代碼](http://www.sqlfiddle.com/#!1/9b879/5) –

+0

+1,完全忘了postgres中的generate_series,我一直在使用SQL Server :) –