分组后的条件求和

如图:
分组后的条件

《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
最佳答案

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


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
3年前 评论
讨论数量: 4
66
select sum(if(status=1,amount,0)) from orders group by created_at;
3年前 评论
select sum(amount), created_at, status from orders group by created_at,status;
3年前 评论

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


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
3年前 评论

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

3年前 评论

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