基于前一个日期的mysql计算

时间:2013-05-22 14:46:15

标签: mysql sql calculated-columns

我有一个奇怪的问题,计算基于从当天的值减去前一天的值 这是查询。示例数据和查询结果here

SELECT pd.id,pd.price_date,pd.name_id,pd.class_id,pd.currency_id,pd.price,
         pd.price - (SELECT price
                    FROM price_data as x
                    WHERE x.price_date < pd.price_date
                    AND x.name_id      = pd.name_id
                    AND x.class_id     = pd.class_id
                    AND x.currency_id  = pd.currency_id
      HAVING MAX(x.price_date)) as `change`
      FROM price_data as pd
      WHERE pd.name_id ='BILL'

      ORDER bY pd.name_id,pd.class_id,pd.currency_id,pd.price_date    

如果查看结果集,您将看到计算有效,直到它在row 6处首次失败。似乎开始将之前的更改添加到当前的更改中。

日期确定有问题吗?

1 个答案:

答案 0 :(得分:0)

您想要的查询是:

SELECT pd.id,pd.price_date,pd.name_id,pd.class_id,pd.currency_id,pd.price,
         pd.price - (SELECT price
                     FROM price_data as x
                     WHERE x.price_date < pd.price_date
                     AND x.name_id      = pd.name_id
                     AND x.class_id     = pd.class_id
                     AND x.currency_id  = pd.currency_id
                     order by x.price_date desc
                     limit 1
                    ) as `change`
FROM price_data as pd
WHERE pd.name_id ='BILL'
ORDER bY pd.name_id,pd.class_id,pd.currency_id,pd.price_date;

原始查询有什么问题?好吧,having子句是非操作的,因为它只是检查price_date的最大值是不是0.要获得你想要的,你需要订购数据并获取你感兴趣的一个值英寸