Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

only return records with odd count in a table with sql command

I have a warehouse table in my Access database that looks like this:

   product_id
       10
       20
       20
       30
       30
       30
       40
       40
       40
       40

Now I need an SQL query to return 10, 30
product_ids which have odd count in the table.

SELECT product_id, Count(product_id) AS cnt
FROM warehouse
GROUP BY product_id;

This query returns the count of each value, but how can I edit it to only return rows with odd cnt?

like image 458
Ali Parsa Avatar asked Mar 07 '26 15:03

Ali Parsa


1 Answers

You could use a having clause with the mod operator:

SELECT   product_id, COUNT(product_id) AS cnt
FROM     warehouse
GROUP BY product_id
HAVING   COUNT(product_id) MOD 2 = 1;
like image 150
Mureinik Avatar answered Mar 10 '26 05:03

Mureinik