考虑下表:
sp100_id _date open close bullishness
-----------------------------------------------
1 2011-03-14 100 110 2.23
1 2011-03-15 115 100 1.00
1 2011-03-16 110 110 0.85
2 2011-03-14 90 85 0.99
2 2011-03-15 95 90 0.30
2 2011-03-16 92 100 4.66
3 2011-03-14 200 220 1.50
3 2011-03-15 250 210 1.75
3 2011-03-16 200 150 0.80
我想计算% return
和bullishness
之间每个股票的2011-03-14
和2011-03-16
,按% return
DESC排名,并返回{{ 1}},sp100_id
和% return
。我认为以下查询可以解决这个问题:
average bullishness
但是,它似乎总是只返回一行。然而,预期的产出是:
SELECT
sp100_id,
AVG(bullishness) as bullishness,
((`close`-`open`) / `open`) as return_pct
FROM
stocks
WHERE _date = BETWEEN '2011-03-14' AND '2011-03-16'
ORDER BY return_pct DESC
我做错了什么?
答案 0 :(得分:3)
您必须在查询中使用GROUP BY
:
SELECT
sp100_id,
AVG(bullishness) as bullishness,
(((SELECT `close` FROM stocks s2
WHERE s2.sp100_id=s1.sp100_id ORDER BY _date DESC LIMIT 1)
-(SELECT `open` FROM stocks s3
WHERE s3.sp100_id=s1.sp100_id ORDER BY _date ASC LIMIT 1)) /
(SELECT `open` FROM stocks s3
WHERE s3.sp100_id=s1.sp100_id ORDER BY _date ASC LIMIT 1)) as return_pct
FROM
stocks s1
WHERE _date BETWEEN '2011-03-14' AND '2011-03-16'
GROUP BY sp100_id
ORDER BY return_pct DESC
如果没有GROUP BY
,它只返回一个结果行,因为AVG
将所有记录组合在一起。
我使用ORDER BY
和LIMIT 1
的子查询修复了return_pct的计算。