Zaffar Saffee
Zaffar Saffee

Reputation: 6305

nested query returning values

I have a table order_details like this

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

My query is

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

my required result is

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

that is, I need two columns for same sku after calculation,

I am unable to establish the logic, I have tried using GROUP BY in nested query, but it doesn't work... any help is highly appreciated.. thanks

UPDATE: trying to do via this but still a failure,

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

Upvotes: 1

Views: 31

Answers (1)

sgeddes
sgeddes

Reputation: 62841

You can use conditional aggregation for this:

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 |

Upvotes: 1

Related Questions