I have the following table:
$ sqlite3 :memory:
BEGIN TRANSACTION;
CREATE TABLE trades (date, stock, buyer, seller, quantity);
INSERT INTO "trades" VALUES(1,'X','A','B',10);
INSERT INTO "trades" VALUES(1,'X','A','C',10);
INSERT INTO "trades" VALUES(1,'Y','C','A',20);
INSERT INTO "trades" VALUES(2,'X','B','A',10);
INSERT INTO "trades" VALUES(2,'Y','B','A',10);
INSERT INTO "trades" VALUES(2,'Z','D','E',11);
COMMIT;
select * from trades;
date stock buyer seller quantity
---------- ---------- ---------- ---------- ----------
1 X A B 10
1 X A C 10
1 Y C A 20
2 X B A 10
2 Y B A 10
2 Z D E 11
I wish to make a summary for each day and each stock, containing the total amount of bought and sold stocks for each broker, i.e. the aggregated activity for each broker for each stock and each day. The output I am looking for is something like this:
select ...magic statement ... from trades;
date stock broker bought sold
---------- ---------- ---------- ---------- ----------
1 X A 20 0
1 X B 0 10
1 X C 0 10
1 Y A 0 20
1 Y B 0 0
1 Y C 20 0
2 X A 0 10
2 X B 10 0
2 X C 0 0
2 Y A 0 10
2 Y B 10 0
2 Y C 0 0
The list of stocks and broker names are not fixed, i.e. they must be retrieved from the table itself (and thus cannot be "hardcoded" in the sql select statement).
Is this possible in a single (SQLite) SQL statement?