gpt4 book ai didi

mysql - 嵌套查询返回值

转载 作者:行者123 更新时间:2023-11-28 23:35:43 27 4
gpt4 key购买 nike

我有一个像这样的表 order_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

我无法建立逻辑,我尝试在嵌套查询中使用 GROUP BY,但它不起作用...非常感谢任何帮助..谢谢

更新:尝试通过此操作但仍然失败,

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

Results:

| SKU | quantity_original | quantity_discount |
|-----|-------------------|-------------------|
| abc | 1 | 99 |
| xyz | 3 | 200 |

关于mysql - 嵌套查询返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35818659/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com