By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
create table my_table as
select 1 as id, date('2020-03-02') as startdate, date('2020-03-02') as enddate union all
select 2, date('2020-04-02') as startdate, date('2020-04-02') as enddate union all
select 3, date('2020-04-02') as startdate, date('2020-05-02') as enddate union all
select 4, date('2020-04-02') as startdate, date('2020-05-02') as enddate union all
select 5, date('2020-05-02') as startdate, date('2020-06-02') as enddate union all
select 6, date('2020-05-02') as startdate, date('2020-06-02') as enddate union all
select 7, date('2020-06-02') as startdate, date('2020-07-02') as enddate
Records: 7 Duplicates: 0 Warnings: 0
Select ifnull(Tb1.mn,Tb2.mn) As mn, ifnull(count_mn_start,0) As count_mn_start, ifnull(count_mn_end,0) As count_mn_end
from
(Select Month(StartDate) as mn, count(id) as count_mn_start
from
my_table
Group by Month(StartDate))Tb1
left Join (Select Month(EndDate) as mn, count(id) as count_mn_end
from my_table
Group by Month(EndDate)) Tb2
on Tb1.mn = Tb2.mn
UNION
Select ifnull(Tb1.mn,Tb2.mn) As mn, ifnull(count_mn_start,0) As count_mn_start, ifnull(count_mn_end,0) As count_mn_end
from
(Select Month(StartDate) as mn, count(id) as count_mn_start
from
my_table
Group by Month(StartDate))Tb1
Right Join (Select Month(EndDate) as mn, count(id) as count_mn_end
from my_table
Group by Month(EndDate)) Tb2
on Tb1.mn = Tb2.mn;
mn | count_mn_start | count_mn_end |
---|---|---|
3 | 1 | 1 |
4 | 3 | 1 |
5 | 2 | 2 |
6 | 1 | 2 |
7 | 0 | 1 |