首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >postgresql - get count by value ranges

postgresql - get count by value ranges
EN

Stack Overflow用户
提问于 2014-10-09 18:46:06
回答 1查看 359关注 0票数 2

我的数据如下所示:

代码语言:javascript
复制
name | value
------------
a    | 3.5
a    | 13.5
a    | 4.9
a    | 11
a    | 14
b    | 2.5
b    | 13.6
b    | 5.1
b    | 12
b    | 13.5

我需要按值范围分组的计数:

代码语言:javascript
复制
name | 0-5 | 5-10 | 10-15
-------------------------
a    | 2   | 0    | 2
b    | 1   | 1    | 3

任何帮助都是非常感谢的。

谢谢,grassu

EN

回答 1

Stack Overflow用户

发布于 2014-10-09 18:48:05

代码语言:javascript
复制
select name, 
       count(case when value <= 5 then 1 end) as "0-5",
       count(case when value > 5 and value <= 10 then 1 end) as "5-10",
       count(case when value > 10 and value <= 15 then 1 end) as "10-15"
from the_table
group by name;

在即将到来的9.4版本中,这可以写得更具可读性:

代码语言:javascript
复制
select name, 
       count(*) filter (where amount <= 5) as "0-5",
       count(*) filter (where value > 5 and value <= 10) as "5-10",
       count(*) filter (where value > 10 and value <= 15) as "10-15"
from the_table
group by name;
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26276454

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档