I have a SQL select statement with multiple UNION ALL
keywords connecting otherwise independent SQL statements. The query is too complex for me to do without the UNION ALL
keywords.
However, I want to limit all of the subqueries to a specific date range and I don't want to write the exact same where clause at the end of each of them. Is there a way I can write one WHERE
clause for all of them?
I tried the following code, but it doesn't work because the COUNT(*)
phrase prevents the inputDate
column from being filtered for every record. Also from a performance standpoint it is probably better to filter by the date column first if there is a way to do that.
SELECT * FROM (
SELECT count(*), inputDate 'sel1' as name FROM tblName WHERE name IN ('n1','n2')
UNION ALL
SELECT count(*), inputDate, 'sel2' as name FROM tblName WHERE name IN ('n3','n4')
UNION ALL
SELECT count(*), inputDate, 'sel3' as name FROM tblName WHERE name IN ('n5','n6')
) names WHERE inputDate >= DATE_SUB(NOW(), INTERVAL 1 MONTH)