FILTER
Postgres 9.4+中的Aggregate 子句
从Postgres 9.4开始,有一种干净快捷的方法(SQL标准):
SELECT count(*) FILTER (WHERE score BETWEEN 0 AND 3) AS low
, count(*) FILTER (WHERE score BETWEEN 4 AND 7) AS mid
, count(*) FILTER (WHERE score BETWEEN 8 AND 10) AS high
, count(*) AS total
FROM foo;
total
加起来low
,mid
并且high
,除非NULL或其他值都参与。
链接:
另请阅读以下内容。
Postgres 9.3-
有两种技术:
@Phil为标准方式提供了一条CASE
语句(除了sum(1)
,这不是标准方式)。我喜欢使用较短的形式:
SELECT count(score BETWEEN 0 AND 3 OR NULL) AS low
, count(score BETWEEN 4 AND 6 OR NULL) AS mid
, count(score BETWEEN 7 AND 10 OR NULL) AS high
, count(*) AS total
FROM foo;
如果你的价值观是你的问题的定义(只0
- 10
可能的话),进一步简化:
SELECT count(score < 4 OR NULL) AS low
, count(score BETWEEN 4 AND 6 OR NULL) AS mid
, count(score > 6 OR NULL) AS high
, count(*) AS total
FROM foo;
短一点,快一点。
细微的差异
有细微的差别相比,sum()
在菲尔的回答:
这些查询中的任何一个(包括Phil在内)都为计数空值total
。如果不希望这样,请改用:
count(score) AS total_not_null
第9.3页中的 SQL Fiddle。
分贝<>小提琴这里在第10页。