Query

SQL每日價值(今天價值 - 昨天價值)

  • March 28, 2021

我有一個有銷售的數據庫。

+----+-----------+------------+
| ID | Quantity  |    DATE    |
+----+-----------+------------+
| 1  |       40  | 2020/10/10 |
| 2  |        0  | 2020/10/01 |
| 3  |       10  | 2020/10/11 |
+----+-----------+------------+

我想要這個結果:

+------------+----------+------------+
| OPERATION  | Resultat |    DATE    |
+------------+----------+------------+
| 40 - 0     |      40  | 2020/10/10 |
| 0 - 40     |     -40  | 2020/10/01 |
| 10 - 0     |      10  | 2020/10/11 |
+------------+----------+------------+

我的意思是得到日期值的總和-昨天的值

有人可以告訴我如何簡單地寫這個嗎?先感謝您

數據不符合您想要的結果,所以我不得不更改日期

架構(SQLite v3.30)

CREATE TABLE table1 (
 `ID` INTEGER,
 `Quantity` INTEGER,
 `DATE` DATE
);

INSERT INTO table1
 (`ID`, `Quantity`, `DATE`)
VALUES
 ('1', '40', '2020/10/10'),
 ('2',  '0', '2020/10/11'),
 ('3', '10', '2020/10/12');

查詢 #1

SELECT 
*,
   Quantity - LAG ( Quantity, 1, 0 ) OVER ( 
       ORDER BY `DATE` 
   ) PreviousYearTotal  
   FROM table1;

| ID  | Quantity | DATE       | PreviousYearTotal |
| --- | -------- | ---------- | ----------------- |
| 1   | 40       | 2020/10/10 | 40                |
| 2   | 0        | 2020/10/11 | -40               |
| 3   | 10       | 2020/10/12 | 10                |

在 DB Fiddle 上查看

引用自:https://dba.stackexchange.com/questions/276838