gpt4 book ai didi

mysql - 是否可以减去 2 个子查询的值并返回差值?

转载 作者:行者123 更新时间:2023-11-30 21:54:31 25 4
gpt4 key购买 nike

这背后的逻辑是我想从已售出的产品中减去退回的产品。这样我就可以销售净数量的产品。子查询返回数值,但我不确定如何从这些子查询中获取差异。

SELECT COUNT(QUANTITY_ORDERED) FROM PRODUCTS
WHERE
(SELECT COUNT(QUANTITY_ORDERED) FROM PRODUCTS WHERE CATEGORY ='SOLD')-(SELECT COUNT(QUANTITY_ORDERED) FROM PRODUCTS WHERE CATEGORY='RETURNED')

最佳答案

只需执行条件 SUM() 而不是 COUNT()

SELECT product_id, 
SUM(CASE WHEN CATEGORY ='SOLD' THEN QUANTITY_ORDERED ELSE 0 END)
- SUM(CASE WHEN CATEGORY ='RETURNED' THEN QUANTITY_ORDERED ELSE 0 END) as total
FROM products
GROUP BY product_id

SELECT product_id, 
COUNT(CASE WHEN CATEGORY ='SOLD' THEN 0 END)
- COUNT(CASE WHEN CATEGORY ='RETURNED' THEN 0 END) as total
FROM products
GROUP BY product_id

关于mysql - 是否可以减去 2 个子查询的值并返回差值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45805619/

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