MYSQL从之前的选定行和行返回数据

时间:2013-09-16 23:39:12

标签: mysql

我有一张表(price_history),显示给定产品的价格历史记录。我想做一个查询,显示当前价格(最近的日期)和之前的价格(最近的日期之前),基本上是旧价格和新价格。这是一个示例表:

| historyid | productcode | optionid | price | date       |
+-----------+-------------+----------+-------+------------+
|      9635 |      254256 |        1 | 42.95 | 1286494361 |
|      9690 |      254256 |        1 | 35.00 | 1286495188 |
|      9727 |      254256 |        1 | 47.95 | 1287529777 |
|      9728 |      254256 |        1 | 40.00 | 1288902624 |

这是我想要的:

| productcode | optionid | Old price |  New Price |  Date      |
+-------------+----------+-----------+------------+------------+
|      254256 |         1|     47.95 |  40.00     | 1288902624 |

我似乎无法弄清楚如何获得我需要的结果。任何帮助将不胜感激。感谢

2 个答案:

答案 0 :(得分:0)

使用以下数据(格式化日期适当):

+-----------+-------------+----------+-------+------------+
| historyid | productcode | optionid | price | validdate  |
+-----------+-------------+----------+-------+------------+
|      9660 |      254256 |        1 | 35.00 | 2013-09-14 |
|      9727 |      254256 |        1 | 47.95 | 2013-09-15 |
|      9728 |      254256 |        1 | 40.00 | 2013-09-16 |
|      9635 |      254256 |        1 | 42.95 | 2013-09-13 |
+-----------+-------------+----------+-------+------------+

要获取最新日期的价格和前一天的价格,请使用:

select a.*, b.price as oldprice
from testing a 
left join testing b 
    on a.validdate = adddate(b.validdate, 1) 
order by a.validdate desc
limit 0, 1;

+-----------+-------------+----------+-------+------------+----------+
| historyid | productcode | optionid | price | validdate  | oldprice |
+-----------+-------------+----------+-------+------------+----------+
|      9728 |      254256 |        1 | 40.00 | 2013-09-16 |    47.95 |
+-----------+-------------+----------+-------+------------+----------+

答案 1 :(得分:0)

如果日期不连续,您可以执行以下操作:

SQL Fiddle

MySQL 5.5.32架构设置

CREATE TABLE price_history
    (`historyid` int, `productcode` int, `optionid` int, `price` double, `date` int)
;

INSERT INTO price_history
    (`historyid`, `productcode`, `optionid`, `price`, `date`)
VALUES
    (9635, 254256, 1, 42.95, 1286494361),
    (9690, 254256, 1, 35.00, 1286495188),
    (9727, 254256, 1, 47.95, 1287529777),
    (9728, 254256, 1, 40.00, 1288902624)
;

查询1

SELECT ph1.productcode,
       ph1.optionid,
       max(ph2.price) AS oldprice,
       ph1.price AS newprice,
       ph1.date
FROM price_history ph1
INNER JOIN price_history ph2 ON ph1.productcode = ph2.productcode AND
                         ph1.optionid = ph2.optionid AND ph2.date  < ph1.date
GROUP BY ph1.productcode, ph1.optionid, ph1.price, ph1.date
ORDER BY ph1.date DESC LIMIT 0,1

<强> Results

| PRODUCTCODE | OPTIONID | OLDPRICE | NEWPRICE |       DATE |
|-------------|----------|----------|----------|------------|
|      254256 |        1 |    47.95 |       40 | 1288902624 |