如何选择1行多行输出的数据(PostgreSQL)

时间:2013-07-27 07:16:43

标签: postgresql

我有像这样的表测试数据

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数据库中选择命令?

2 个答案:

答案 0 :(得分:4)

试试这个:

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

这是demo

答案 1 :(得分: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