Вы можете попробовать это.
Я думаю, что вы ищете агрегатная функция условия
Схема (MySQL v5.7)
CREATE TABLE payments(
user_id INT,
amount INT,
payment_time DATE,
sale_type VARCHAR(50)
);
INSERT INTO payments VALUES (1,20,'2011-01-31','card');
INSERT INTO payments VALUES (1,10,'2012-01-02','cash');
INSERT INTO payments VALUES (3,10,'2012-01-03','card');
INSERT INTO payments VALUES (4,15,'2012-02-05','bank');
Запрос № 1
select (case when p2.amount <=10 then '0-10'
else '10 and more' end) diapason,
sum(p1.amount) total_amount,
SUM(CASE WHEN p1.sale_type='card' THEN p1.amount ELSE 0 END) card,
SUM(CASE WHEN p1.sale_type='cash' THEN p1.amount ELSE 0 END) cash,
SUM(CASE WHEN p1.sale_type='bank' THEN p1.amount ELSE 0 END) bank
from
(
select *
from payments
where payment_time between '2012-01-01' and '2012-01-30' group by user_id, sale_type
) p1
join (select user_id, sum(amount) amount
from payments
group by user_id) p2
on p1.user_id = p2.user_id
GROUP BY (case when p2.amount <=10 then '0-10'
else '10 and more' end);
| diapason | total_amount | card | cash | bank |
| ----------- | ------------ | ---- | ---- | ---- |
| 0-10 | 10 | 10 | 0 | 0 |
| 10 and more | 10 | 0 | 10 | 0 |
Просмотр на БД Fiddle