0

I need to run a query 1000 times, and add the results to a table. I have the following code which is what I would like to be repeated:

Select max_gridco, count(max_gridco) as TaxLots, sum(population) as pop_sum
from
(
    Select tlid, max_gridco, population
    from (
        select tlid, max_gridco, population, st_intersects(tle.geom, acres025.geom)
        from tle, acres025
        where max_gridco not in (0, 1)
        order by RANDOM()
        limit 1000
    ) as count
    where st_intersects = 't'
    order by max_gridco
) as gridcode_count
group by max_gridco;

Is there a way that I can run this 1000 times automatically, and in the output table have a column that includes the run number? So my table would look like the following:

Run number | max_gridco | TaxLots | pop_sum

I am trying to do a Loop command in PgAdmin3, but cannot seem to get the syntax correct.

2
  • So you need to insert 1000 values to a table by using a select, right? Commented Jun 8, 2017 at 0:52
  • No. I'm sorry my first post was confusing. I was having trouble putting it into words. I edited the post to make my question clearer. Commented Jun 8, 2017 at 1:34

2 Answers 2

2

use DO block or create a function, eg:

DO
$$
begin
for i in 1..1000 loop
    insert into save_to_table (Run number,max_gridco,TaxLots,pop_sum)
    Select i, max_gridco, count(max_gridco) as TaxLots, sum(population) as pop_sum
    from
    (
        Select tlid, max_gridco, population
        from (
            select tlid, max_gridco, population, st_intersects(tle.geom, acres025.geom)
            from tle, acres025
            where max_gridco not in (0, 1)
            order by RANDOM()
            limit 1000
        ) as count
        where st_intersects = 't'
        order by max_gridco
    ) as gridcode_count
    group by max_gridco;
end loop;
end;
$$
;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. That is exactly what I was looking for.
0

If you need to insert values from a specific select you can do it by using:

INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;

(https://www.w3schools.com/sql/sql_insert_into_select.asp)

Is that what you're looking for?

1 Comment

No. Sorry, I guess I should have been more clear. The query that I have above selects 1000 random rows from a table that I have and summarizes the outputs. It outputs six rows: an identifying number, a count of taxlots, and a sum of population. I am looking to automate the results - repeating the query 1000 times, and listing the output table per run.

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.