1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
DROP TABLE IF EXISTS gift_cards CASCADE;
DROP TABLE IF EXISTS transactions;
CREATE TABLE gift_cards(
id INT PRIMARY KEY,
amount NUMERIC(15, 5)
);
CREATE TABLE transactions(
id SERIAL PRIMARY KEY,
payment NUMERIC(15, 5),
gift_card_id INT,
created_at TIMESTAMP,
FOREIGN KEY (gift_card_id) REFERENCES gift_cards(id)
);
INSERT INTO gift_cards(id, amount) VALUES (1, 8.43);
INSERT INTO transactions(payment, gift_card_id, created_at) VALUES (10, 1, '19/09/2016');
INSERT INTO transactions(payment, gift_card_id, created_at) VALUES (-10, 1, '20/09/2016');
INSERT INTO transactions(payment, gift_card_id, created_at) VALUES (50, 1, '08/05/2017');
INSERT INTO transactions(payment, gift_card_id, created_at) VALUES (-21.21, 1, '12/07/2017');
INSERT INTO transactions(payment, gift_card_id, created_at) VALUES (-28.79, 1, '16/05/2018');
INSERT INTO transactions(payment, gift_card_id, created_at) VALUES (45, 1, '30/12/2019');
INSERT INTO transactions(payment, gift_card_id, created_at) VALUES (-33.37, 1, '27/07/2020');
INSERT INTO transactions(payment, gift_card_id, created_at) VALUES (-3.20, 1, '10/09/2020');
SELECT c.id AS gift_card_id, t.id AS transaction_id, t.payment AS transaction_payment,
--la somme des transactions antérieures plus le montant de la transaction en cours,
(SELECT SUM(t2.payment) FROM transactions AS t2 WHERE t.gift_card_id = t2.gift_card_id AND t2.created_at <= t.created_at) AS amount_ligne,
LAG(t.payment, 1) OVER ( ORDER BY created_at) --si j'ai bien suivi le but est de remplacer le select du dessus par le LAG ?
created_at
FROM gift_cards AS c INNER JOIN transactions AS t ON c.id = t.gift_card_id; |
Partager