计算总数和部分数

时间:2014-06-06 21:53:58

标签: sql postgresql count aggregate-functions

我在PostgreSQL引擎驱动的数据库中有一个表answers,其中一个数字与一个问题相关联。我需要计算有多少数字,以及有多少数字低于6,按问题分组。

我想要的是:

SELECT question, count(*) AS Qanswers, count_below_6(*) AS Qanswers_below_6
FROM answers
GROUP BY question;

      question         | Qanswers | Qanswers_below_6
-----------------------+----------+------------------
How do you feel?       |  1234    |      53
Was clear the webinar? |  8444    |      20
How much that hurt?    |  3666    |     142

目前我正在做

SELECT question, count(*) AS Qanswers
FROM answers
GROUP BY question;

然后

SELECT question, count(*) AS Qanswers
FROM answers
WHERE value < 6
GROUP BY question;

之后我手动合并两个结果 我可以根据需要制作一个能给我结果的单句吗?

1 个答案:

答案 0 :(得分:0)

SELECT question
      ,count(*) AS answers
      ,count(value < 6 OR NULL) AS under_6
FROM   answers
GROUP  BY question;

诀窍是count(expression)仅计算非空值(而count(*)计算所有行)。这里详细解释了为什么我们在正确的地方得到NULL:
Compute percents from SUM() in the same SELECT sql query

有许多等效技术可以实现这一目标。与基准的详细比较:
For absolute performance, is SUM faster or COUNT?