您可以在子查询中计算桶,然后在外部查询中进行条件聚合:
select
amount_range,
sum(type = 'A') typeA,
sum(type = 'B') typeB,
sum(type = 'C') typeC,
sum(type = 'D') typeD,
count(*) all_types
from (
select t.*,
case
when amount > 1100 then '1001-1300'
when amount > 900 then '901-1100'
when amount > 700 then '701-900'
else '500-700'
end as amount_range
from mytable
where amount between 500 and 1300
) t
group by amount_range
实际上,没有真正需要子查询。在 MySQL 中,你可以这样做:
select
case
when amount > 1100 then '1001-1300'
when amount > 900 then '901-1100'
when amount > 700 then '701-900'
else '500-700'
end as amount_range,
sum(type = 'A') typeA,
sum(type = 'B') typeB,
sum(type = 'C') typeC,
sum(type = 'D') typeD,
count(*) all_types
from mytable
where amount between 500 and 1300
group by amount_range
编辑
如果您想要记录总数的比率,请使用窗口函数(在 MySQL 8.0 中可用):
select
case
when amount > 1100 then '1001-1300'
when amount > 900 then '901-1100'
when amount > 700 then '701-900'
else '500-700'
end as amount_range,
sum(type = 'A')/sum(count(*)) over() typeA_ratio,
sum(type = 'B')/sum(count(*)) over() typeB_ratio,
sum(type = 'C')/sum(count(*)) over() typeC_ratio,
sum(type = 'D')/sum(count(*)) over() typeD_ratio,
count(*)/sum(count(*)) over() all_types_ratio
from mytable
where amount between 500 and 1300
group by amount_range