一种方法是使用条件求和(对于单独列中的值):
select sum(case when col1 <= 15000 then 1 else 0 end) as range1,
sum(case when col1 > 15001 and col1 <= 30000 then 1 else 0 end) as range2,
sum(case when col1 > 30001 and col1 <= 45000 then 1 else 0 end) as range3
from tbl1;
另一种方法是使用group by
(对于单独行上的值):
select (case when col1 <= 15000 then 'range1'
when col1 > 15001 and col1 <= 30000 then 'range2'
when col1 > 30001 and col1 <= 45000 then 'range3'
else 'other'
end) as range, count(*) as cnt
from tbl1
group by (case when col1 <= 15000 then 'range1'
when col1 > 15001 and col1 <= 30000 then 'range2'
when col1 > 30001 and col1 <= 45000 then 'range3'
else 'other'
end);
我经常对这种形式使用子查询:
select range, count(*)
from (select t.*,
(case when col1 <= 15000 then 'range1'
when col1 > 15001 and col1 <= 30000 then 'range2'
when col1 > 30001 and col1 <= 45000 then 'range3'
else 'other'
end) as range
from tbl1
group by range;
这样, 的定义range
只出现一次。
编辑:
以上都使用了OP的逻辑。但是,上述逻辑忽略了15001
和的值30001
。我的猜测是 OP 真的意味着col1 > 15000 and col1 <= 30000
和col1 > 30000 and col1 <= 45000
条件。15001
但是,我不会更改它们,因为以上是原始问题的措辞方式(也许and有一些特别之处30001
)。