简体   繁体   English

MYSQL-GROUP BY和COUNT查询

[英]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. 使用下面的查询,我得到一个标题为“ widget”的所有行的漂亮列表,并对每个类别中有多少行进行计数。 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 我想最后列出一个列表,该列表显示类别3中有多少个以及所有其他类别中有多少个,因此结果将是

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? 我可以用2个查询来做,一个查询得到全部计数,另一个查询得到catid 3计数,然后减去它们,但是用一个查询可以吗?

You could use CASE expression: 您可以使用CASE表达式:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM