SELECT totalAmount
FROM tbl
BETWEEN 'date1' AND 'date2'
GROUP BY DATE(date created)
ORDER BY DATE(date created)
这给了我表中每天的总金额。但我想要的是与前一个条目(不一定是前一天)相比的增量值
表格可能类似于:
totalAmount | date created
---------------------------------
1000 | 1st Jan
1001 | 2nd Jan
1003 | 3rd Jan
1008 | 15th Jan
所以我的查询会返回: 1000,1001,1003,1008。
我真正想要的是: (与之前的条目相比较的数字 - 但不在BETWEEN日期范围内,以便开始我的实施),1,2,5
答案 0 :(得分: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
答案 1 :(得分:0)
试试这个:
SELECT totalAmount
FROM tbl
BETWEEN 'date1' AND 'date2'
GROUP BY DATE(date created)
ORDER BY totalAmount DESC, DATE(date created)
答案 2 :(得分: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