My initial question is posted here (In psql how to run a Loop for a Select query with CTEs and get the output shown in read-only db?), which isn't defined well, so I am creating new question here. I want to know how can I use a loop variable (or something similar) inside a Select query with CTEs . I hope the following is a minimal reproducible example:
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
insert into persons values (4,'Smith','Eric','713 Louise Circle','Paris');
insert into persons values (5,'Smith2','Eric2','715 Louise Circle','London');
insert into persons values (8,'Smith3','Eric3','718 Louise Circle','Madrid');
Now I run the following for different values of (1,2,3)
WITH params AS
(
SELECT <ROWNUMBER> AS rownumber ),
person AS
(
SELECT personid, lastname, firstname, address
FROM params, persons
ORDER BY personid DESC
LIMIT 1
OFFSET ( SELECT rownumber - 1
FROM params) ),
filtered AS
(
SELECT *
FROM person
WHERE address ~ (SELECT rownumber::text FROM params)
)
SELECT *
FROM filtered;
and getting these outputs respectively for 1,2 and 3:
| personid | lastname | firstname | address
|----------|----------|-----------|-------------------
| 8 | Smith3 | Eric3 | 718 Louise Circle
(1 row)
| personid | lastname | firstname | address
|----------|----------|-----------|---------
(0 rows)
| personid | lastname | firstname | address
|----------|----------|-----------|-------------------
| 4 | Smith | Eric | 713 Louise Circle
(1 row)
My goal is to have a single query with loop or any other means to get the union of all 3 above select runs. I only have read-only access to db, so can't output in a new table. The GUI software I use have options to output in an internal window or export to a plain text file. The desired result would be:
|personid | lastname | firstname | address
|----------|----------|-----------|-------------------
| 4 | Smith | Eric | 713 Louise Circle
| 8 | Smith3 | Eric3 | 718 Louise Circle
(2 rows)
In reality the the loop variable is used in a more complicated way.