mysqlnullzerogroup

How to Group 0 with NULL in mysql select


I know there are many variants of this question, but none seem to address my issue.

I have a page reporting website order stats. One of the variables it considers is which 'website' a customer used. The website ids are integers, but for historical reasons, one of them is stored as either 0 or NULL. I need to group them together in my query.

I know I could update all NULL entries to 0 in that row of the db, but a lot of changes would need to be made to prevent more being added.

My original query was:

SELECT o.website, p.orderid, count(p.orderid) ordercount
FROM gdd_order as o, gdd_process as p 
WHERE o.orderid = p.orderid 
AND p.prog_return >= '2024-03-01' 
AND p.prog_return < '2024-03-31'  
GROUP BY o.website 
ORDER BY FIELD(o.website,0,5,1,2,3,4)

which returns

website orderid ordercount
(NULL) 92914 76
0 93256 48
5 92916 74
1 92908 136

I tried:

SELECT ifnull(o.website, 0) website, p.orderid, count(p.orderid) ordercount
FROM gdd_order as o, gdd_process as p 
WHERE o.orderid = p.orderid 
AND p.prog_return >= '2024-03-01' 
AND p.prog_return < '2024-03-31'  
GROUP BY o.website 
ORDER BY FIELD(o.website,0,5,1,2,3,4)

which makes NULL zero, but doesn't group the 'null 0' row in with the '0' row:

website orderid ordercount
0 92914 76
0 93256 48
5 92916 74
1 92908 136

How do I combine the '0' and 'NULL 0' data in a single row?


Solution

  • Use IFNULL(o.website, 0) consistently throughout the query.

    SELECT ifnull(o.website, 0) website, p.orderid, count(p.orderid) ordercount
    FROM gdd_order as o, gdd_process as p 
    WHERE o.orderid = p.orderid 
    AND p.prog_return >= '2024-03-01' 
    AND p.prog_return < '2024-03-31'  
    GROUP BY IFNULL(o.website, 0)
    ORDER BY FIELD(IFNULL(o.website, 0),0,5,1,2,3,4)