Question

My question is made of 3 parts.

First part:
Is there a way to generate rows based on a value?

E.g:
I want to give each family a number of vouchers based on their family_members_count. Each voucher should have a unique id:

Base table:

id name family_members_count
1  fadi 2
2  sami 3
3  ali  1

Result:

family_id     name      voucher_id 
1             fadi      121
1             fadi      122
2             sami      123
2             sami      124
2             sami      125
3             ali       126

Second part:
Can I control the voucher_id composite key? I want the voucher_id to be like this

(location)(cycle)(sequence 5 digits)

If north = 08 and we are in the second cycle it should be:

080200001
080200002

... and so on.

Third part:
I need the solution in both MS Access 2010 SQL and PostgreSQL 9.1 SQL.

Was it helpful?

Solution

Question 1

Use generate_series(). (In the coming version 9.3 look for the key word LATERAL.)

SELECT id AS family_id
      ,name
      ,120 + generate_series(1, family_members_count) AS voucher_id 
FROM fam;

-> sqlfiddle demo

Question 2

SELECT id AS family_id
      ,name
      ,location 
       || to_char(cycle, 'FM00')
       || to_char(generate_series(1, family_members_count), 'FM00000')
          AS voucher_id 
FROM fam2;

-> sqlfiddle demo

Question 3

Sorry, I got MS Access out of my system 10 years ago and never looked back. Somebody else might fill in. I doubt it will be as simple.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top