我想从单个查询中的表格中选择最近200,100和50行收盘价的 SUM 。 下面给出的是200行的查询。
SELECT SUM(Close_price) as tot200 FROM cash_data ORDER BY date_added LIMIT 0,200
任何人都可以帮助我。
答案 0 :(得分:3)
您可以使用子查询 -
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
答案 1 :(得分:1)
要在没有任何子选择的单个选择中进行制作,您可以使用排名变量和有条件的总和
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
答案 2 :(得分:0)
感谢所有回复。实际上两个答案都有效,但我选择了第二个,并根据我的需要做了一些改变。以下是最终查询
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
谢谢大家。