假设我有一个名为people
的数据库:
有id
和type
我如何计算 属于特定类型的人。
我不想要像这样的查询,我想自动执行此操作:
SELECT
COUNT(CASE WHEN type = 'single' THEN 1 END) as single,
COUNT(CASE WHEN type = 'married' THEN 1 END) as marrried,
COUNT(CASE WHEN type = 'kids' THEN 1 END) as kids
......
FROM people;
我该怎么做?致谢
答案 0 :(得分:1)
使用分组
SELECT COUNT(id), type FROM people GROUP BY type
答案 1 :(得分:0)
与你的最接近的技巧是:
SELECT
SUM(CASE WHEN type = 'single' THEN 1 ELSE 0 END) as single,
SUM(CASE WHEN type = 'married' THEN 1 ELSE 0 END) as marrried,
...