计算属于特定类型的条目

时间:2015-03-30 13:37:42

标签: sql postgresql

假设我有一个名为people的数据库:

idtype

我如何计算 属于特定类型的人

我不想要像这样的查询,我想自动执行此操作:

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;

我该怎么做?致谢

2 个答案:

答案 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,
  ...