CheeseFlavored
CheeseFlavored

Reputation: 2112

MYSQL - GROUP BY and COUNT query

I have a database containing rows like this

title          category
-----------------------
super widget      1
ultimate widget   1
regular widget    1
happy widget      2
sad widget        2
ugly widget       3
pretty widget     3

using the query below, I get a nice list of all rows with a title like "widget" and a count of how many are in each category. so the result would look like

catid   itemcount
-------------------
1           3
2           2
3           2

SELECT catid, COUNT(*) AS 'itemcount' FROM allwidgets
 WHERE title like '%widget%' GROUP BY catid;

I need to alter this. I want to end up with a list that shows how many are in category 3 and how many are in all other categories so the result would be

catid   itemcount
------------------
3           2
allothers   5

I could do it with 2 queries, one to get the full count and another to get catid 3 count, then subtract them, but is it possible with one query?

Upvotes: 0

Views: 27

Answers (1)

Lukasz Szozda
Lukasz Szozda

Reputation: 175566

You could use CASE expression:

SELECT CASE WHEN catid = 3 THEN '3' ELSE 'allothers' END AS catid,COUNT(*) AS itemcount 
FROM allwidgets
WHERE title like '%widget%' 
GROUP BY CASE WHEN catid = 3 THEN '3' ELSE 'allothers' END;

Upvotes: 2

Related Questions