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

Count total without duplicate records

I have a table that contains the following columns: TrackingStatus, Year, Month, Order, Notes

I need to calculate the total number of tracking status for each year and month.

For example, if the table contains the following orders:

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

TrackingStatus Year Month Order Notes
F 2020 1 33
F 2020 1 33 DFF
E 2020 2 36 xxx
A 2021 3 34 X1
A 2021 3 34 DD
A 2021 3 88
A 2021 2 45

The result should be:

• Tracking F , year 2020, month 1 the total will be one (because it’s the same year, month, and order).
• Tracking A , year 2021, month 2 the total will be one. (because there is only one record with the same year, month, and order).
• Tracking A , year 2021, month 3 the total will be two. (because there are two orders within the same year and month).

So the expected SELECT output will be like that:

TrackingStatus Year Month Total
F 2020 1 1
E 2020 2 1
A 2021 2 1
A 2021 3 2

I was trying to use group by but then it will count the number of records which in my scenario is wrong.

How can I get the total orders for each month without counting “duplicate” records?

Thank you

>Solution :

You can use a COUNT DISTINCT aggregation function, whereas the COUNT allows you to count the values, but the DISTINCT condition will allow each value only once.

SELECT TrackingStatus,
       Year,
       Month,
       COUNT(DISTINCT Order) AS Total
FROM tab
GROUP BY TrackingStatus,
         Year,
         Month
ORDER BY Year, 
         Month

Here you can find a tested solution in a MySQL environment, though this should work with many DBMS.

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