Question

I have a database where there are sales .

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

And i want this result :

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

I mean get the sum of the value of date - value of yersterday

could someone give me an idea of how i could write this simply? Thank you in advance

Was it helpful?

Solution

The data don't fit your wanted resukt, so i had t change the date#

Schema (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');

Query #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                |

View on DB Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top