2014-10-09 61 views
1

我的數據是這樣的:PostgreSQL的 - 得到由價值數範圍

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 

我需要值範圍分組計數:

name | 0-5 | 5-10 | 10-15 
------------------------- 
a | 2 | 0 | 2 
b | 1 | 1 | 3 

任何幫助表示讚賞。

感謝, grassu

回答

4
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版本,這個可以寫多一點可讀性:

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; 
+0

thanksa很多。太簡單。 – user1288241 2014-10-09 10:57:27