SQL query count customers

Viewed 68

I need count how many suppliers have status "CLOSED" or "READY FOR AUDIT", but in the same time I don't want to count those suppliers that have status "NULL".

supplier status
JUSTRITE MANUFACTURING COMPANY CLOSED
JW SPEAKER CORPORATION CLOSED
KLEIN TOOLS INC NULL
KLEIN TOOLS INC CLOSED
KLEVER INNOVATIONS CLOSED
LA-CO INDUSTRIES INC CLOSED

As we can see in this example, there are 5 different customers, but the results will be "4" because KLEINT contains "NULL" and it shouldn't be counted in.

4 Answers

Let's say table is defined like the following:

Table name: your_table with two fields

supplier          status    
----------------  ------  

Then you can get the result by aggregation function count.

SELECT 
   supplier,
   SUM(IFNULL((SELECT 1 FROM your_table WHERE a. supplier = supplier LIMIT 1), 0)) AS cnt
FROM your_table a
WHERE `status` IN ('CLOSED', 'READY')
GROUP BY supplier
HAVING cnt > 0
;

I have made a fiddle for you with the solution as an example

https://www.db-fiddle.com/f/rW914i1yUA5GBK2d9j6PGB/0

also the code should look like this

SELECT count(*)
FROM test
WHERE STATUS IS NOT NULL
    AND STATUS IN (
        'CLOSED'
        ,'READY FOR AUDIT'
        )

this code ignores NULL values, (but they have to be empty values, not someone typing NULL in the fields. that makes a diffrence)

You can:

  • select all suppliers which have "CLOSED" or "READY FOR AUDIT" status
  • remove from the selection all those that have a "NULL" status
SELECT COUNT(DISTINCT supplier) 
FROM tab 
WHERE status IN ('CLOSED', 'READY FOR AUDIT')
  AND supplier NOT IN (SELECT supplier FROM tab WHERE status IS NULL) 

Check the demo here.

WITH CTE(COMPANY,STATUSS) AS
(
   SELECT  'JUSTRITE MANUFACTURING COMPANY',  'CLOSED' UNION ALL
   SELECT'JW SPEAKER CORPORATION',          'CLOSED' UNION ALL
   SELECT'KLEIN TOOLS INC' ,                NULL UNION ALL
   SELECT'KLEIN TOOLS INC' ,                'CLOSED' UNION ALL
   SELECT'KLEVER INNOVATIONS',              'CLOSED' UNION ALL
   SELECT'LA-CO INDUSTRIES INC'  ,          'CLOSED'
)
SELECT COUNT(C.COMPANY)
FROM CTE AS C
WHERE C.STATUSS IN('CLOSED','READY FOR AUDIT')
AND NOT EXISTS
(
   SELECT 1 FROM CTE AS X WHERE C.COMPANY=X.COMPANY AND X.STATUSS IS NULL
)

CTE is an example of your data. Please replace it with your table name

Related