I want to select SUM of last 200,100 and 50 rows of close price from a table in a single query. given below is the query for 200 rows.
SELECT SUM(Close_price) as tot200 FROM cash_data ORDER BY date_added LIMIT 0,200
can anyone help me with this.
You can use sub queries -
SELECT
(SELECT SUM(Close_price) FROM cash_data ORDER BY date_added LIMIT 0,200) as tot200,
(SELECT SUM(Close_price) FROM cash_data ORDER BY date_added LIMIT 0,100) as tot100,
(SELECT SUM(Close_price) FROM cash_data ORDER BY date_added LIMIT 0,50) as tot50
To make it in a single select without any subselects you can use a ranking varaible and sum conditionally
SELECT @rank := @rank + 1,
SUM(case when @rank <= 50 then Close_price else 0 end) as top_50_sum,
SUM(case when @rank <= 100 then Close_price else 0 end) as top_100_sum,
SUM(case when @rank <= 200 then Close_price else 0 end) as top_200_sum
FROM cash_data
cross join (select @rank := 0) r
ORDER BY date_added
LIMIT 0,200
Thanks for all the replies. Actually both the answers are working but i choose the second one and made some changes for my need. Below is the final query
SELECT
(SELECT SUM(Close_price)/200 FROM (SELECT Close_price FROM cash_data WHERE SERIES='$series' AND SYMBOL='$symbol' AND date_added <= '$date' ORDER BY date_added DESC LIMIT 0,200) as tot200) as avg200,
(SELECT SUM(Close_price)/100 FROM (SELECT Close_price FROM cash_data WHERE SERIES='$series' AND SYMBOL='$symbol' AND date_added <= '$date' ORDER BY date_added DESC LIMIT 0,100) as tot100) as avg100,
(SELECT SUM(Close_price)/50 FROM (SELECT Close_price FROM cash_data WHERE SERIES='$series' AND SYMBOL='$symbol' AND date_added <= '$date' ORDER BY date_added DESC LIMIT 0,50) as tot50) as avg50
Thank you all.