Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Sum of a column grouped by another column then grouped into another

I've been trying for a while now to figure this out but my lack of more advanced SQL skills are holding me back.

Executions(TradeDate, Symbol, Side, Price, Under, Account)

TEMP DATA:
2012-06-20, AAPL 120716C00600000, BUY, 3.25, AAPL, XYZ123
2012-06-20, AAPL 120716C00600000, SELL, 3.30, AAPL, XYZ123
2012-06-20, AAPL 120716C00600000, BUY, 3.25, AAPL, XYZ123
2012-06-20, AAPL 120716C00600000, SELL, 3.30, AAPL, XYZ123
2012-06-20, GRPN 120716C00027000, BUY, 2.25, GRPN, XYZ123
2012-06-20, GRPN 120716C00027000, SELL, 2.30, GRPN, XYZ123
2012-06-20, GRPN 120716C00027000, SELL, 2.30, GRPN, XYZ123
2012-06-20, GRPN 120716C00027000, BUY, 2.25, GRPN, XYZ123


-UNDER----Side(Buy)----Side(Sell)
 AAPL      6.50         6.60
 GRPN      4.50         4.60

As you can see I'm trying to get the SUM of the Price for each Side and then grouped by the Under.

like image 244
Stephen Gilboy Avatar asked Jan 16 '23 06:01

Stephen Gilboy


1 Answers

Use GROUP BY to group by Under column and CASE associated with SUM to get the needed results:

SELECT e.Under,
       SUM(case when e.Side = 'BUY' them e.Price else 0 end) as 'Side(Buy)',
       SUM(case when e.Side = 'SELL' them e.Price else 0 end) as 'Side(Sell)'
FROM Executions e
GROUP BY e.Under
like image 138
aF. Avatar answered Jan 24 '23 22:01

aF.