我有一张像这样的表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
答案 0 :(得分:1)
您可以使用conditional aggregation
:
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 |