您可以使用聚合函数内部的CASE表达式,将得到的结果列:
SELECT
COUNT(case when amount >= 0 and amount <= 100 then users.id end) Amt0_100,
COUNT(case when amount >= 101 and amount <= 200 then users.id end) Amt101_200,
COUNT(case when amount >= 201 and amount <= 300 then users.id end) Amt201_300
FROM transactions
LEFT JOIN users
ON users.id = transactions.user_id;
见SQL Fiddle with Demo
你会发现,我改变了范围从0到100,101 -200,201-300,否则你将有用户id在100,200的值上计数两次。
如果你想在每行的值,那么你可以使用:
select count(u.id),
CASE
WHEN amount >=0 and amount <=100 THEN '0-100'
WHEN amount >=101 and amount <=200 THEN '101-200'
WHEN amount >=201 and amount <=300 THEN '101-300'
END Amount
from transactions t
left join users u
on u.id = t.user_id
group by
CASE
WHEN amount >=0 and amount <=100 THEN '0-100'
WHEN amount >=101 and amount <=200 THEN '101-200'
WHEN amount >=201 and amount <=300 THEN '101-300'
END
见SQL Fiddle with Demo
但如果你有,你需要在计算计数许多范围,那么你可能想考虑范围创建表,类似于以下内容:
create table report_range
(
start_range int,
end_range int
);
insert into report_range values
(0, 100),
(101, 200),
(201, 300);
然后你就可以使用此表加入到当前的表和组由RAN ge值:
select count(u.id) Total, concat(start_range, '-', end_range) amount
from transactions t
left join users u
on u.id = t.user_id
left join report_range r
on t.amount >= r.start_range
and t.amount<= r.end_range
group by concat(start_range, '-', end_range);
参见SQL Fiddle with Demo。
如果你不想创建范围的新表,那么你可以随时使用派生表来获得相同的结果:
select count(u.id) Total, concat(start_range, '-', end_range) amount
from transactions t
left join users u
on u.id = t.user_id
left join
(
select 0 start_range, 100 end_range union all
select 101 start_range, 200 end_range union all
select 201 start_range, 300 end_range
) r
on t.amount >= r.start_range
and t.amount<= r.end_range
group by concat(start_range, '-', end_range);
见SQL Fiddle with Demo
为什么不只是三个查询? –
这只是一个简单的例子,实际上我需要更多的范围。 –