【问题标题】:how to SUM a column by different condition then group by date如何按不同条件对列求和,然后按日期分组
【发布时间】:2021-05-13 22:12:12
【问题描述】:

我尝试将列(小计)的值汇总到不同列(总计、拒绝、实际)中,这些列根据列的条件(状态)进行区分。

实际表(ode_orders)

Delivery Date Subtotal State
1/2/2021 150.00 Delivery Completed
2/2/2021 45.00 Rejected by business
2/2/2021 45.00 Delivery Completed
2/2/2021 87.00 Rejected by business
3/2/2021 45.00 Delivery Completed
3/2/2021 70.00 Delivery Completed

我希望它成为新表:

Delivery Date Total Sales Rejected Actual
1/2/2021 150 0 150
2/2/2021 177 132 45
3/2/2021 155 0 155

我尝试使用此查询:

SELECT  delivery_date, 
  SUM(subtotal) AS TotalSale,
  SUM(subtotal) WHERE state NOT LIKE %Completed% AS TotalSale
FROM ode_orders
GROUP BY delivery_date;

结果

Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE state NOT LIKE %Completed% AS TotalSale
FROM ode_orders
GROUP BY deliver' at line 3

【问题讨论】:

    标签: mysql sql group-by sum


    【解决方案1】:

    使用条件聚合

     SELECT delivery_date, SUM(subtotal) AS TotalSale,
     SUM(case when State='Rejected by business' then subtotal else 0 end) as Rejected ,
    SUM(case when State='Delivery Completed' then subtotal else 0 end) as actual 
     from table_name group by delivery_date
    

    【讨论】:

    • 谢谢你!另一个问题是如何按日期添加订单总数?就像我们已经得到了实际的总量,但是如果我们也计算一下总订单的数量会更好。例如,总共 10 个订单 RM150。
    • 如果有助于标记为已接受,只需计数(*)以及已回答的查询即可
    • 我已经得到了所有的总数。但是当我按“拒绝”条件计算时,它会计算所有行,我想排除“已完成”条件。 @zaynul
    【解决方案2】:
    select * 
    ,(totalSales-Rejected) Actual
    from
      (
      select deliveryDate 
      ,sum(subTotal) totalSales 
      ,isnull((
      select sum(subTotal)  from ode_orders sa where sa.deliveryDate=a.deliveryDate and 
      [state]='Rejected by business'
      ),0) Rejected
      from ode_orders a
      group by deliveryDate
    ) mt
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-06
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      相关资源
      最近更新 更多