我有一个包含这样的行的数据库
title category
-----------------------
super widget 1
ultimate widget 1
regular widget 1
happy widget 2
sad widget 2
ugly widget 3
pretty widget 3
使用下面的查询,我得到一个漂亮的所有行列表,其标题为“ widget”,并统计每个类别中有多少行。所以结果看起来像是
catid itemcount
-------------------
1 3
2 2
3 2
SELECT catid, COUNT(*) AS 'itemcount' FROM allwidgets
WHERE title like '%widget%' GROUP BY catid;
我需要对此进行更改。我想最后列出一个列表,该列表显示类别3中有多少,所有其他类别中有多少,因此结果将是
catid itemcount
------------------
3 2
allothers 5
我可以用2个查询来完成此操作,一个查询获得完整计数,另一个查询获得catid 3计数,然后减去它们,但是用一个查询可以吗?
答案 0 :(得分:2)
您可以使用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;