表格包含以下字段

时间:2016-01-28 08:36:08

标签: mysql sql

ID    Datetime    Price 
1     25Jan       10
1     26Jan       11
2     23JAN       12
2     24JAN       13

我想要以下结果

ID    Datetime    (Daytime-1)    (PRice for today)    (LastDayprice)
1     26 JAN      25 JAN         11                   10
2     24JAN       23 JAN         13                   12

有关SQL的任何帮助都将不胜感激!

2 个答案:

答案 0 :(得分:0)

SELECT t.ID,t.Datetime,s.datetime as yesterday,t.price,s.price as yest_price
FROM YourTable t
LEFT OUTER JOIN YourTable s
ON t.id = s.id and t.datetime = s.datetime+1

这应该可以解决问题。

答案 1 :(得分:0)

这很有效。

SQLFiddle Demo

SELECT prv.id, 
       cur.datetime, 
       prv.datetime AS "Daytime-1", 
       cur.price    AS "PRice for today", 
       prv.price    AS LastDayprice 
FROM   table1 prv 
       left join (SELECT id, 
                         datetime, 
                         price 
                  FROM   table1) cur 
              ON prv.id = cur.id 
                 AND prv.datetime = Date_sub(cur.datetime, interval 1 day) 
WHERE  cur.id IS NOT NULL