如何計算mysql中每個前一行的百分比差異?mysql與上一行的百分比差異
我能得到這個工作,但如果我的date
列不連續的,我不知道如何動態地把它:
SELECT c1.date,
c1.total,
((c1.total - ifnull(c2.total, 0))/c1.total) AS percentage_change
FROM table c1
LEFT OUTER JOIN table c2
ON c1.id = c2.id
AND c1.date - c2.date = 1
ORDER BY c1.date DESC
LIMIT 30
這個麻煩的是,我的date
列不一定c1.total - c2.total = 1
我的一個想法是做一個子查詢和select where c2.date < c1.date order by c2.date DESC LIMIT 1
。我認爲會選擇下一個最低日期值,所以現在就試試。
男孩哦,男孩,正在做這頓飯的人,不是嗎?!考慮提供適當的DDL(和/或一個sqlfiddle)與期望的結果集合 – Strawberry