2016-03-05 172 views
1

我有一个表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试过,但它不工作... 任何帮助,高度赞赏.. 感谢

UPDATE: 尝试通过做这不过还是失败,

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 

回答

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 | 
+0

+1,真棒....太感谢了,你让我很快乐的老板......一两件事,好像你已经互换列名(原已经成为折扣)但这不是问题,有你的逻辑,谢谢十亿...你真的帮了很多... –

+0

啊...你已经纠正它,再次感谢... –