使用group by将范围内的最大值与特定日期进行比较

时间:2015-04-01 10:52:56

标签: mysql

我希望mysql查询检查结束日期的高值是否大于该符号从结束日期-1天开始的一年范围内的所有高值。

MAX with group by并使用正确的符号进行检查以进行比较。我该如何继续这个?

我的表结构是:

id  Symbol date        high
1   ABC    2015-01-23  45
2   ABC    2015-01-22  40
3   ABC    2014-01-28  33
4   xyz    2015-01-23  37
5   xyz    2015-01-20  70
6   ANO    2015-01-20  170
7   JE     2015-01-25  560
8   JE     2015-01-23  770


SELECT `symbol`,`high` as current_high from history as h 
where date='2015-01-23' 
AND symbol = 'ABC';

SELECT `date`,`symbol`, MAX(`high`) as 1_yrhigh from history 
where date between '2014-01-23' 
and '2015-01-22' AND symbol='ABC'

如果current_high>需要结果1yr_high

所以从上面的示例表的查询结果应该是

1 ABC    2015-01-23  45

8 JE    2015-01-23  770

xyz未显示为37 < max,即70

ANO未显示为2015-01-23没有记录

1 个答案:

答案 0 :(得分:0)

为了在查询

下面使用每个符号的当前高位
Select symbol,MAX(high) as currentHigh
From table
Where date=CURDATE()
Group By symbol

为了获得除当前日期之外的最后1年高,请使用以下查询

Select symbol,MAX(high) as lastOneYrHigh
From table
Where date between (CURDATE()-INTERVAL 1 DAY-INTERVAL 1 YEAR)-(CURDATE() - INTERVAL 1 DAY)  
Group By symbol