简体   繁体   中英

MYSQL math in a single column in a table. Subquery not grouping correctly

I am trying to perform math on a single column in a single table called "actions". The table looks something like this:

Shopper ID   ItemID  Action
1            200     Purchase
1            200     Purchase
1            200     Return
2            100     Purchase
2            100     Return
3            200     Purchase
3            100     Purchase

I want to get a net purchases quantity for each itemID from the above table structure, ie purchases minus returns. Each row is one transaction, so I am using count to derive the quantities. The desired result would look like this:

ItemID   Qty_Purch   Qty_returned  Net_qty_purchased
100      2           1             1
200      3           1             2

My query below has a grouping problem, it adds all the purchases and all the returns in the entire table for each itemID, so the result I get is this:

ItemID   Qty_Purch   Qty_returned  Net_qty_purchased
100      5           2             3
200      5           2             3

My current query looks like this:

create table MYDB.purch0 as
SELECT ItemId,
(Select Count(w1.ItemID) FROM MYDB.actions w1 where w1.action in ("Purchase")) as Qty_Purch,
(Select Count(w2.ItemID) FROM MYDB.actions w2 where w2.action in ("Return  ") ) as Qty_Returned,
(Select  Count(w3.ItemID) FROM MYDB.actions w3 where w3.action in ("Purchase")) -
(Select  Count(w4.ItemID) FROM MYDB.actions w4 where w4.action in ("Return  "))  as Net_qty_purchased

FROM MYDB.actions w
group by itemID

Please help me to get to the desired output. Thanks in anticipation.

You can use conditional aggregation to get the results you want, taking advantage of the fact that MySQL treats a boolean as 1 or 0 in a numeric context:

SELECT ItemID,
       SUM(Action = 'Purchase') AS Qty_purch,
       SUM(Action = 'Return') AS Qty_returned,
       SUM(Action = 'Purchase') - SUM(Action = 'Return') AS Net_qty_purchased
FROM actions
GROUP BY ItemID

Output:

ItemID  Qty_purch   Qty_returned    Net_qty_purchased
100     2           1               1
200     3           1               2

Demo on dbfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM