2016-03-05 230 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

啊...你已經糾正它,再次感謝... –