[英]Select sum of column according to case statement in mysql query
I have a table with three columns: 1. store name 2. data type (sales, return) 3. qty 我有一个包含三列的表:1.商店名称2.数据类型(销售,退货)3.数量
---------------------------
| Stores | Data | Qty |
---------------------------
| HM | Sales | 15 |
| RD | Sales | 10 |
| HM | Return | 4 |
| RD | Return | 2 |
I want to select all store names, sales qty, return qty as following 我要选择所有商店名称,销售数量,返回数量,如下所示
--------------------------
| Store | Sales | Return |
--------------------------
| HM | 15 | 4 |
| RD | 10 | 2 |
Here's what I've tried: 这是我尝试过的:
SELECT store,
CASE `data`
WHEN 'Sales' THEN SUM(qty)
ELSE NULL
END as `Sales`,
CASE `data`
WHEN 'Return' THEN SUM(qty)
ELSE NULL
END as `Return`
FROM `full_report`
GROUP BY store
Result: I get wrong sales qty and Null for return qty! 结果:我得到错误的销售数量,而退货数量为空!
You can use conditional aggregation . 您可以使用条件聚合。 . 。 . 。 mixing case
with sum()
: 与sum()
混合case
:
select fr.store,
SUM(case when fr.data = 'Sales' then fr.qty else 0 end) as Sales,
SUM(case when fr.data = 'Return' then fr.qty else 0 end) as Returns
from full_report fr
group by fr.store;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.