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

Mysql query to get the distinct count by current year and last year on the same date

I am trying to get the distinct count of (ordno,partno) by the date for current year and last year..Please find below the DDL for the input and the output tables.

Create table input
(ordno varchar(20),
partno varchar(40),
orddate date)

insert into input values
('BC132','13211','4/1/2022'),
('NM121','8901','4/1/2022'),
('JK121','90122','4/1/2022'),
('NM121','9021','4/1/2021'),
('KL123','634','4/1/2021'),
('OP121','453','4/1/2021'),
('KL121','6781','4/1/2021'),
('KL1234','93211','4/15/2022'),
('OQ121','431','4/15/2022'),
('HJ121','321','4/15/2022'),
('M213','221','4/15/2022'),
('B121','901','4/15/2022')


Create table output
(orddate date,
currentyear int,
last year int)

insert into output values
('Apr 01',3','4'),
('Apr 15',3','2')

Thanks,
Arun

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

>Solution :

Your expected result and create table statement and data examples doesn’t match each other.

I used proper date datatype and used DATE_FORMAT to give your expected format.

Try:

select  DATE_FORMAT(orddate,'%b %d') as my_date,
       count(case when YEAR(orddate)='2022' then partno  end) as currentyear,
       count(case when YEAR(orddate)='2021' then partno  end) as last_year  
from input
group by my_date;

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=7ef1f4ccf86a8089834a589db6fe4ffa

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