You need dynamic SQL for that. SQL does not accept the dynamic conversion of literals / values to identifiers. So you need to build the query first and then execute it. You can do this in your client (seems to be Java), or do it all inside Postgres, which is generally fastest:
SELECT $$SELECT sum(user_count) AS user_count_sum
,sum(min_count) AS min_count_sum
,sum(max_count) AS max_count_sum
FROM (
($$
||
string_agg(format($$
SELECT max(case when di = 'i' then di_count end) AS user_count
,min(di_count) AS min_count
,max(di_count) AS max_count
FROM (
SELECT di, count(distinct rt) AS di_count
FROM %I
WHERE rt > now() - interval '1 day'
GROUP BY 1
) t
)$$, tbl)
,'
UNION ALL
(')
|| '
) sub'
FROM mastertable;
Produces the query-string:
SELECT sum(user_count) AS user_count_sum
,sum(min_count) AS min_count_sum
,sum(max_count) AS max_count_sum
FROM (
(
SELECT max(case when di = 'i' then di_count end) AS user_count
,min(di_count) AS min_count
,max(di_count) AS max_count
FROM (
SELECT di, count(distinct rt) AS di_count
FROM gpstablev2
WHERE rt > now() - interval '1 day'
GROUP BY 1
) t
)
UNION ALL
(
SELECT max(case when di = 'i' then di_count end) AS user_count
,min(di_count) AS min_count
,max(di_count) AS max_count
FROM (
SELECT di, count(distinct rt) AS di_count
FROM powertablev2
WHERE rt > now() - interval '1 day'
GROUP BY 1
) t
)
UNION ALL
...
) sub;
GETDATE()
is not a valid Postgres function. You probably meannow()
orCURRENT_DATE
.. depending on the undisclosed type ofrt
. I usenow()
instead.You most probably want to use
UNION ALL
instead ofUNION
here.Also fixed missing aliases for subqueries and made some minor simplifications.
Wrap this into a plpgsql function with EXECUTE
. There are plenty of closely related examples here on SO with code and links and explanation ...