Mysql 嵌套查询返回值
我有一张这样的表格Mysql 嵌套查询返回值,mysql,sql,select,group-by,Mysql,Sql,Select,Group By,我有一张这样的表格order\u details id | SKU | quantity_purchased | discount_price --------------------------------------------------- 1 | abc | 1 | 10.0 2 | abc | 90 | 00 2 | abc | 9
order\u details
id | SKU | quantity_purchased | discount_price
---------------------------------------------------
1 | abc | 1 | 10.0
2 | abc | 90 | 00
2 | abc | 9 | 00
3 | xyz | 1 | 50.0
3 | xyz | 2 | 50.0
4 | xyz | 100 | 00
4 | xyz | 100 | 00
-----------------------------------------------
我的问题是
select
(select sum(quantity_purchased) from order_details where discount_price > 0.00) as qty_discount,
(select sum(quantity_purchased) from order_details where discount_price = 0.00)as qty_original,
sku
from order_details
GROUP BY sku
我要求的成绩是
SKU | quantity_original | quantity_discount
---------------------------------------------------
abc | 1 | 99
xyz | 3 | 200
-----------------------------------------------
也就是说,在计算之后,我需要为相同的sku
设置两列
我无法建立逻辑,我已尝试在嵌套查询中使用groupby
,但不起作用。。。
非常感谢您的帮助。。
谢谢
更新:
试图通过这个来做,但还是失败了
select
(select sum(quantity_purchased) from order_details where discount_price > 0.00 ) as qty_discount,
(select sum(quantity_purchased) from order_details where discount_price = 0.00 )as qty_original,
sku
from order_details
where sku = (select distinct sku from order_details)
GROUP BY sku
您可以为此使用
条件聚合
:
select sku,
sum(case when discount_price != 0 then quantity_purchased
else 0
end) quantity_original,
sum(case when discount_price = 0 then quantity_purchased
else 0
end) quantity_discount
from order_details
group by sku
+1、太棒了……万分感谢,你让我当了“每日老板”……有一件事,看起来你已经交换了列名(原来的列名已经打折了),但这不是问题,你有你的逻辑,感谢万分……你真的帮了大忙。。。
Results:
| SKU | quantity_original | quantity_discount |
|-----|-------------------|-------------------|
| abc | 1 | 99 |
| xyz | 3 | 200 |