EDIT: mysql version: 5.7.34
I am querying my data to get counts on different group, I'm doing it in one query using union (see this question)
here is my query
SELECT 'department' as group_name, department, NULL AS d_type, NULL AS country, NULL AS city, COUNT(trx.id)
FROM (<some query>) trx
GROUP BY department
UNION ALL
SELECT 'd_type', NULL, d_type, NULL, NULL, COUNT(trx.id)
FROM (<some query>) trx
GROUP BY d_type
UNION ALL
SELECT 'location', NULL, NULL, NULL, country, city, COUNT(trx.id)
FROM (<some query>)
GROUP BY country, city
this is my 'some query':
SELECT IFNULL(parent_id, child_id) as id, department, d_type, country, city
FROM my_table
WHERE <some conditions..>
GROUP BY id
is there a way I can use the 'some query' in all unions with out writing it each time, and with running it only once? (currently it runs for each union)