2012-02-06 140 views
1

我想使一個MySQL從表中誰看起來像這樣每天都得到差值:MySQL查詢獲得每日差異值

Date    | VALUE 
-------------------------------- 
"2011-01-14 19:30" | 5 
"2011-01-15 13:30" | 6 
"2011-01-15 23:50" | 9 
"2011-01-16 9:30" | 10 
"2011-01-16 18:30" | 15 

我做了兩個子查詢。第一個是拿到最後的日常價值,因爲我想從這個數據計算差值:

SELECT r.Date, r.VALUE 
    FROM table AS r 
    JOIN (
    SELECT DISTINCT max(t.Date) AS Date 
    FROM table AS t 
    WHERE t.Date < CURDATE() 
    GROUP BY DATE(t.Date) 
    ) AS x USING (Date) 

第二個是由獲得從第一個結果的差值(我秀它與「表」的名稱):

SELECT Date, VALUE - IFNULL( 
    (SELECT MAX(VALUE) 
    FROM table 
    WHERE Date < t1.table) , 0) AS diff 
    FROM table AS t1 
    ORDER BY Date 

起初,我想第一個查詢的結果保存在臨時表,但it's not possible to use temporary tables with the second query。如果我在()與別名之間的第二個FROM內使用第一個查詢,那麼關於表別名的服務器投訴不存在。如何獲得這樣的事情:

Date    | VALUE 
--------------------------- 
"2011-01-15 00:00" | 4 
"2011-01-16 00:00" | 6 

回答

2

嘗試此查詢 -

SELECT 
    t1.dt AS date, 
    t1.value - t2.value AS value 
FROM 
    (SELECT DATE(date) dt, MAX(value) value FROM table GROUP BY dt) t1 
JOIN 
    (SELECT DATE(date) dt, MAX(value) value FROM table GROUP BY dt) t2 
    ON t1.dt = t2.dt + INTERVAL 1 DAY 
+0

感謝,它的工作原理就像一個魅力。 – 2012-02-06 11:28:38