0

有两个表:

* ORDER 
  - id
  - pay_type
* ORDER_PRICE
  - order_id
  - dt
  - price

订单价格可以更改,例如:

order_id | price | dt  
       1 | 100.3 | 2013-10-25  
       1 | 105.7 | 2013-10-28  
       2 | 207.4 | 2013-09-13  
       4 | 98.0 | 2013-10-03

我可以选择任何日期的价格历史记录:

 SELECT 
o.`id`,
    (SELECT op.`price` FROM `order_price` op 
     WHERE op.`order_id`=o.`id` AND op.`dt` <= '2013-10-26'
     ORDER BY op.`dt` DESC LIMIT 1) order_price
    FROM `order` o 

它给了我给定日期的正确价格

order_id | price | dt  
       1 | 100.3 | 2013-10-25   
       2 | 207.4 | 2013-09-13  
       4 |  98.0 | 2013-10-03

但我需要第二列的总和(无论什么订单号,只有一个数字 - 在这种情况下为 405.7)。

这种情况有解决办法吗?可能有数千个订单,所以我认为在mysql之外汇总记录是错误的。也许从一开始就是错误的,我需要其他结构?感谢您的时间和帮助。

4

1 回答 1

0

我怀疑核心查询应该看起来更像这样......

      SELECT o.order_id
           , op.price
           , op.dt
        FROM orders o 
        JOIN order_price op
          ON op.order_id = o.order_id
        JOIN 
           ( SELECT order_id, MAX(dt) max_dt FROM order_price WHERE dt < '2013-10-26' GROUP BY order_id ) x
          ON x.order_id = op.order_id 
         AND x.max_dt = op.dt;

...可以这样重写,给出总数

SELECT o.order_id
     , SUM(op.price) price
     , op.dt
  FROM orders o 
  JOIN order_price op
    ON op.order_id = o.order_id
  JOIN 
     ( SELECT order_id, MAX(dt) max_dt FROM order_price WHERE dt < '2013-10-26' GROUP BY order_id ) x
    ON x.order_id = op.order_id 
   AND x.max_dt = op.dt
 GROUP
    BY order_id,dt
  WITH ROLLUP;

...或者这样

SELECT SUM(price) total 
FROM
 ( SELECT o.order_id
       , op.price
       , op.dt
    FROM orders o 
    JOIN order_price op
      ON op.order_id = o.order_id
    JOIN 
       ( SELECT order_id, MAX(dt) max_dt FROM order_price WHERE dt < '2013-10-26' GROUP BY order_id ) x
      ON x.order_id = op.order_id 
     AND x.max_dt = op.dt
 ) z;

...或者只是在应用程序级别提取总数。

于 2013-11-09T09:42:40.563 回答