mysql根据订单状态拆分和添加列

6g8kf2rb  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(362)

这是我要修改的查询

select 
o.orders_id, 
o.customers_id, 
o.customers_name, 
s.orders_status_name, 
ot.text as order_total, 
ot.value as value,
datediff(now(), payment_data_read_status) as numdaysleft, 
sum(ifnull(op.paid_total, 0)) paid_total 
from orders o 
join orders_total ot 
on o.orders_id = ot.orders_id 
join orders_status s 
on o.orders_status = s.orders_status_id 
left outer join ( select orders_id, sum(ifnull(paid_amount, 0)) as paid_total from orders_payment where confirm_payment = '1' group by orders_id ) op on op.orders_id = o.orders_id where ot.class = 'ot_total' and s.language_id = '1' and round(ot.value,2) != round(ifnull(op.paid_total, 0), 2) 
GROUP by o.customers_id 
ORDER BY paid_total DESC

每个客户都有自己的订单,订单完成、注入、等待付款确认等不同的状态,我想实现的是对订单价值的求和 ot.value 对于每个客户的所有订单 s.orders_status_name =“订单完成”并在新列中显示为“已完成订单总数”。同样地,未处于“订单完成”状态的订单也应相加 ot.value 并在新列中显示为“未完成订单和”
这是每个客户机的数据

fjaof16o

fjaof16o1#

你需要一个

sum(case when s.orders_status_name= "Order Complete" 
      then ot.value
      else 0
end) as completed_orders_sum

.

select 
o.orders_id, 
o.customers_id, 
o.customers_name, 
s.orders_status_name, 
ot.text as order_total, 
sum(case when s.orders_status_name= "Order Complete" 
      then ot.value
      else 0
end ) as completed_orders_sum
datediff(now(), payment_data_read_status) as numdaysleft, 
sum(ifnull(op.paid_total, 0)) paid_total 
from orders o 
join orders_total ot 
on o.orders_id = ot.orders_id 
join orders_status s 
on o.orders_status = s.orders_status_id 
left outer join ( select orders_id, sum(ifnull(paid_amount, 0)) as paid_total 
                        from orders_payment 
                        where confirm_payment = '1' group by orders_id ) op on op.orders_id = o.orders_id 
                              where ot.class = 'ot_total' and s.language_id = '1' and round(ot.value,2) != round(ifnull(op.paid_total, 0), 2) 
GROUP by o.customers_id

相关问题