如何制作几列?

时间:2018-09-08 21:05:10

标签: mysql sql database join select

我需要在几列中显示结果吗?

样本数据

payments
user_id     amount     payment_time   sale_type
1           20          31.01.2011     card
1           10          02.01.2012     cash
3           10          03.01.2012     card
4           15          05.02.2012     bank

我需要结果:

diapason     total_amount    card     cash     bank
0-10              10     
10 and more       10     

真实查询

select IFnull(t.diapason,'total') as diapason, t.total_amount as 
total_amount, t.cash, t.bank 
FROM 
(SELECT CASE
when p2.amount<=10 then '0-10'
when p2.amount>10 then '10 +' END AS diapason, 
sum(p1.amount) as total_amount,
SUM(CASE WHEN p1.sale_type='cash' THEN p1.amount ELSE 0 END) as cash,
SUM(CASE WHEN p1.sale_type='bank' THEN p1.amount ELSE 0 END) as bank
FROM 
(SELECT distinct user_id, SUM(amount) AS amount, sale_type FROM payments 
where payment_time between '2018-04-12' and '2018-04-18' group by user_id) 
p1 
inner JOIN 
(SELECT DISTINCT user_id, sum(amount) AS amount FROM payments group by 
user_id) p2 
on p1.user_id = p2.user_id 
GROUP BY diapason WITH ROLLUP) t;

这是真实的查询,但给出错误的结果

1 个答案:

答案 0 :(得分:2)

您可以尝试一下。

我认为您正在寻找条件汇总函数

模式(MySQL v5.7)

dir_two

查询#1

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');

View on DB Fiddle