0

I have data on table test like this

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

Now,i want to select from table test with multiple output that calculate by value of field chance

output like this

customer_no | name
------------------
00000000001 | AAAA
00000000001 | AAAA
00000000001 | AAAA
00000000002 | BBBB
00000000002 | BBBB
00000000003 | CCCC

how to select command in pgsql database?

2 Answers 2

4

Try this:

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

Here is a demo.

Sign up to request clarification or add additional context in comments.

1 Comment

+1, totally forgot about generate_series in postgres, i'm working with SQL Server all the time :)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.