分组后的条件求和

如图:
分组后的条件

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案

有种做大学作业的感觉。。。


select 
  t1.created_at, 
  sum(t1.total_0) as 'amount_0', 
  sum(t1.total_1) as 'amount_1' 
from 
  (
    select 
      t.created_at, 
      (
        case t.status when 1 then t.amount end
      ) as 'total_0', 
      (
        case t.status when 2 then t.amount end
      ) as 'total_1' 
    from 
      (
        select  created_at, status, sum(amount) as 'amount'  from   orders  group by created_at, status
      ) as t
  ) as t1 
group by  created_at

更简洁的

select  created_at,
sum(case status when 1 then amount end) as 'total_1',
sum(case status when 0 then amount end) as 'total_2'
from   orders  group by created_at
2年前 评论
讨论数量: 4
66
select sum(if(status=1,amount,0)) from orders group by created_at;
2年前 评论
select sum(amount), created_at, status from orders group by created_at,status;
2年前 评论

有种做大学作业的感觉。。。


select 
  t1.created_at, 
  sum(t1.total_0) as 'amount_0', 
  sum(t1.total_1) as 'amount_1' 
from 
  (
    select 
      t.created_at, 
      (
        case t.status when 1 then t.amount end
      ) as 'total_0', 
      (
        case t.status when 2 then t.amount end
      ) as 'total_1' 
    from 
      (
        select  created_at, status, sum(amount) as 'amount'  from   orders  group by created_at, status
      ) as t
  ) as t1 
group by  created_at

更简洁的

select  created_at,
sum(case status when 1 then amount end) as 'total_1',
sum(case status when 0 then amount end) as 'total_2'
from   orders  group by created_at
2年前 评论

数据量大的话,这种查询很慢,建议用内存换速度,外加一个统计表

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!