Currently I have 2 tables in SQL Server: tab_master (current month table) and tab_08_2022 (indicating it refers to Aug data based on the timestamp).
The tables have exactly structures, the only difference being they pertain to different months.
There will be more tables coming in for subsequent months: tab_08_2022, tab_09_2022, tab_10_2022 and so on.
I need to count the number of rows for each flag (grouping by the flag column) and showcase them every month. This should also have the data from all the previous month's tables.
For one table the query could be:
select count(*), flag_col
from tab_master
group by flag_col;
When the second table comes in the query would be
select *
from
(select count(*), flag_col
from tab_master
group by flag_col) x
inner join
(select count(*), flag_col as flag_08_2022
from tab_09_2022
group by flag_col) y on x.flag = y.flag_08_2022;
When the third table comes in the query would be
select *
from
(select count(*), flag_col
from tab_master
group by flag_col) x
inner join
(select count(*), flag_col as flag_08_2022
from tab_08_2022
group by flag) y on x.flag = y.flag_08_2022
inner join
(select count(*), flag_col as flag_09_2022
from tab_09_2022
group by flag_col) z on x.flag_col = z.flag_09_2022;
How do I go about doing that?