如何使用限制

时间:2017-05-29 06:27:22

标签: mysql sql join

我需要计算" final"的平均值。特定日期和ID的符号列,这里id是主列日期是唯一列,目前我在下面使用查询

select   s1.id, avg_final(s1.date,s1.symbol,5) as short_vg 
from final_data s1 where s1.date = p_date;

上面的查询是一个过程的一部分,p_date输入到过程,这里我想删除函数" avg_final"这需要很长时间,

以下功能需要删除:

             DROP FUNCTION IF EXISTS avg_final;
             CREATE FUNCTION avg_final(p_date datetime,p_symbol
             varchar(50),avg_int INT) RETURNS decimal(20,2)
             BEGIN
                DECLARE income decimal(20,2);
                select avg(dd.final_value) into income from
                (select  * from final_data a where a.symbol = p_symbol and a.date
             <= p_date order by a.date desc limit avg_int) dd;
               RETURN income;
             END;

我在下面尝试过查询它需要在sub之间进行适当的关联 运行此查询后,它会为v.symbol

抛出错误
select
 (
  select
    (select s.id from final_data s where s.date = max(asd.date)
and s.symbol = asd.symbol) as maxid,  avg(asd.final_value) as avg_val
from
    (select sd.* from final_data sd where sd.symbol=v.symbol and
sd.id = v.id order by date desc limit 5) asd ) from final_data v.

(我正在使用Mysql)

以下是样本数据和预期的avg_final值:

+----------------------------------------------------------------+
|id    |  final_value | date              |  symbol |   avg_final|
+----------------------------------------------------------------+
|1     |  20.00       |1/1/2014 0:00:00   |  MUMBAI |87          |
|2     |  55.00       |1/1/2014 0:00:00   |  DELHI  |33          |
|3     |  30.00       |1/2/2014 0:00:00   |  MUMBAI |            |
|4     |  15.00       |1/2/2014 0:00:00   |  DELHI  |            |
|5     |  40.00       |1/3/2014 0:00:00   |  MUMBAI |            |
|6     |  45.00       |1/4/2014 0:00:00   |  MUMBAI |            |
|7     |  60.00       |1/3/2014 0:00:00   |  DELHI  |            |
|8     |  300.00      |1/5/2014 0:00:00   |  MUMBAI |            |
|9     |  30.00       |1/4/2014 0:00:00   |  DELHI  |            |
|10    |  5.00        |1/5/2014 0:00:00   |  DELHI  |            |
+----------------------------------------------------------------+

样本数据也显示在图像

0 个答案:

没有答案