0

我有这样的表格测试数据

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

4

2 回答 2

4

尝试这个:

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

这是一个演示

于 2013-07-27T07:45:25.437 回答
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 提琴示例

于 2013-07-27T07:33:43.347 回答