Home > Mobile >  Count total without duplicate records
Count total without duplicate records

Time:06-03

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:

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

CodePudding user response:

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.

  •  Tags:  
  • sql
  • Related