3

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

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. 似乎开始将先前的更改添加到当前更改中。

日期确定有问题吗?

4

1 回答 1

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。要得到你想要的,你需要对数据进行排序并取你感兴趣的一个值。

于 2013-05-22T15:19:00.597 回答