I have a bunch of table that have a "stat" column (stat for status ;-)
I would like the count of each stats, and see it!
My tables look like this
create table a (
a_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
a_stat status_t
);
create table b (
b_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
b_stat status_t
);
status_t
is an enum.
So I did this:
DO $$
DECLARE
tableName RECORD;
result RECORD;
BEGIN
SET SEARCH_PATH = projet, public;
FOR tableName IN SELECT
c.relname,
a.attname
FROM pg_class AS c
INNER JOIN pg_attribute AS a ON a.attrelid = c.oid
WHERE a.attname LIKE '%stat' AND c.relkind = 'r' LOOP
EXECUTE format('SELECT %I, count(%I) FROM %I GROUP BY %I',
tableName.attname, tableName.attname, tableName.relname, tableName.attname) INTO result;
SELECT * FROM result;
END LOOP;
END;
$$;
There are things that I think I'm not doing well here.
- There is maybe a better form of format
- I can't select a RECORD, I think the datatype is not good (but can't figure out what type I should use)
- A select inside a for loop is not a good idea (I think ?) But I didn't found How to put
result
into a array of result, and display it after the for loop.
How to do this properly?