Home > Net >  How to merge two query results joining same date
How to merge two query results joining same date

Time:10-07

let's say there's a table have data like below

id status date
1 4 2022-05
2 3 2022-06

I want find count of id of each month by their status. Something like this below

date count(status1) = 4 count(status2) =3
2022-05 1 null
2022-06 null 1

I tried doing

-- select distinct (not working)

select date, status1, status2 from 
(select date, count(id) as "status1" from myTable
where status = 4 group by date) as myTable1
join
(select date, count(id) as "status2" from myTable
where status = 3 group by date) as myTable2
on myTable1.date = myTable2.date;

-- group by (not working)

but it does duplicate the data needed. and I am using SQL Server.

CodePudding user response:

select d.date,
 sum
 (
    case 
      when d.status=4 then 1
      else 0
    end
 )count_status_4,
 sum
 (
    case 
      when d.status=5 then 1
      else 0
    end
 )count_status_5
from your_table as d
group by d.date
  • Related