我有下表:
$ 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
我希望为每一天和每只股票做一个总结,包含每个经纪人买入和卖出股票的总量,即每个经纪人对每只股票和每一天的汇总活动。我正在寻找的输出是这样的:
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
股票列表和经纪人名称不是固定的,即它们必须从表本身中检索(因此不能在 sql select 语句中“硬编码”)。
这可以在单个(SQLite)SQL 语句中实现吗?