2009-04-08 87 views
3
SELECT  totalAmount 
FROM  tbl 
BETWEEN  'date1' AND 'date2' 

GROUP BY DATE(date created) 
ORDER BY DATE(date created) 

這給了我表中每天的總金額。但我要的是相比前項增量值(不一定是前一天)從tbl'value1'中減去'上一個值'

表可能是這樣的:

totalAmount | date created 
--------------------------------- 
1000   | 1st Jan 
1001   | 2nd Jan 
1003   | 3rd Jan 
1008   | 15th Jan 

那麼,我的查詢將返回: 1000,1001, 1003,1008。

什麼其實我想要的是:(相比之前的條目數 - 但不是內BETWEEN日期範圍,以便開始我的incriments) ,1,2,5-

+2

當然,你可以創建一個變量,存儲它,然後再使用它返回的每一行? – Kezzer 2009-04-08 10:54:17

回答

1

這有啥可做到這一點:

SELECT IFNULL((t1.totalamount - t2.totalamount),0) as diff, t1.date_created 
FROM view t1 LEFT OUTER JOIN view t2 
ON t2.date = (SELECT MAX(date) FROM view WHERE date < t1.date) 
WHERE t1.date_created BETWEEN 'date1' AND 'date2' 
ORDER BY date_created 

其中,「意見」是這樣的查詢:

SELECT date_created, SUM(totalamount) FROM tbl GROUP BY date_created 
0

試試這個:

SELECT  totalAmount 
FROM  tbl 
BETWEEN  'date1' AND 'date2' 

GROUP BY DATE(date created) 
ORDER BY totalAmount DESC, DATE(date created) 
+0

我認爲你誤解了這個問題 – ed209 2009-04-08 11:23:19

0

您需要加入兩個相同的排名子查詢。我沒有一個MySQL數據庫來測試這對但形式將類似於:

select t1.TotalAmount, t1.DateCreated, 
    t1.TotalAmount - t2.TotalAmount as 'Delta' 
from 
(select rownum, TotalAmount 
from tbl 
order by DateCreated) t1 
left outer join 
(select rownum, TotalAmount 
from tbl 
order by DateCreated) t2 
on t1.rownum = t2.rownum + 1 
order by t1.rownum 
+0

我不認爲mysql在SQL服務器上有一個「rownum」的等價物,所以這在他的情況下不起作用。 – 2009-04-08 12:35:40

+0

SQL Server沒有它,它有一個row_number()函數。我很快搜索了它,並認爲這個函數在MySQL中。有可能是一個解決方法:http://snippets.aktagon.com/snippets/156-MySQL-rownum-equivalent – 2009-04-08 12:41:59