views:

411

answers:

3

A single row in a table has a column with an integer value >= 1 and must be selected however many times the column says. So if the column had '2', I'd like the select query to return the single-row 2 times.

How can this be accomplished?

A: 

You can do it with a recursive query, check out the examples in the postgresql docs.

something like

WITH RECURSIVE t(cnt, id, field2, field3) AS (
        SELECT 1, id, field2, field3
        FROM foo
      UNION ALL
        SELECT t.cnt+1, t.id, t.field2, t.field3
        FROM t, foo f
        WHERE t.id = f.id and t.cnt < f.repeat_cnt
)
SELECT id, field2, field3 FROM t;
Charlie
Only in 8.4 which is only beta still.
rfusca
A: 

You could make a table that is just full of numbers, like this:

CREATE TABLE numbers
(
  num INT NOT NULL
, CONSTRAINT numbers_pk PRIMARY KEY (num)
);

and populate it with as many numbers as you need, starting from one:

INSERT INTO numbers VALUES(1);
INSERT INTO numbers VALUES(2);
INSERT INTO numbers VALUES(3);
...

Then, if you had the table "mydata" that han to repeat based on the column "repeat_count" you would query it like so:

SELECT mydata.*
FROM mydata
JOIN numbers
ON numbers.num <= mydata.repeat_count
WHERE ...

If course you need to know the maximum repeat count up front, and have your numbers table go that high.

No idea why you would want to do this thought. Care to share?

Evan
If whoever the down-voter was reads this, care to share why? Not wanting to argue, just curious for my own edification.
Evan
+4  A: 

Don't know why you would want to do such a thing, but...

CREATE TABLE testy (a int,b text);
INSERT INTO testy VALUES (3,'test');
SELECT testy.*,generate_series(1,a) from testy;  --returns 3 rows
rfusca