Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to merge two query results joining same date

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

-- 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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading