[英]SUM multiple columns by different condition from same table and then group by date
[英]how to SUM a column by different condition then group by date
我試圖將一列(小計)的值匯總到不同的列(總計、拒絕、實際)中,這些列通過列的條件(狀態)來區分。
實際表 (ode_orders)
交貨日期 | 小計 | State |
---|---|---|
2021 年 1 月 2 日 | 150.00 | 交付完成 |
2021 年 2 月 2 日 | 45.00 | 被商家拒絕 |
2021 年 2 月 2 日 | 45.00 | 交付完成 |
2021 年 2 月 2 日 | 87.00 | 被商家拒絕 |
2021 年 3 月 2 日 | 45.00 | 交付完成 |
2021 年 3 月 2 日 | 70.00 | 交付完成 |
我希望它成為新表:
交貨日期 | 總銷售額 | 被拒絕 | 實際的 |
---|---|---|---|
2021 年 1 月 2 日 | 150 | 0 | 150 |
2021 年 2 月 2 日 | 177 | 132 | 45 |
2021 年 3 月 2 日 | 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
使用條件聚合
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
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.