我们看看orders创建的表如下:
架构 (MySQL v8.0)
CREATE TABLE orders (
`trade_date` DATETIME,
`ticker` VARCHAR(4),
`trans_type` VARCHAR(4),
`quantity` INTEGER
);
INSERT INTO orders
(`trade_date`, `ticker`, `trans_type`, `quantity`)
VALUES
('2020-12-10', 'FB', 'BUY', '100'),
('2020-12-28', 'FB', 'BUY', '50'),
('2020-12-29', 'FB', 'SELL', '80'),
('2020-12-30', 'FB', 'SELL', '30'),
('2020-12-31', 'FB', 'BUY', '40'),
('2020-11-16', 'AAPL', 'BUY', '30'),
('2020-11-17', 'AAPL', 'SELL', '70'),
('2020-11-20', 'AAPL', 'BUY', '50'),
('2020-11-24', 'AAPL', 'BUY', '40');
我们想将quantity 与trans_type 相加:
查询 #1
SELECT
trade_date,
ticker,
trans_type,
quantity,
SUM(CASE WHEN trans_type='SELL' THEN -quantity ELSE quantity END) OVER () AS net_quantity
FROM
orders;
我们会得到这张表:
| trade_date |
ticker |
trans_type |
quantity |
net_quantity |
| 2020-12-10 00:00:00 |
FB |
BUY |
100 |
130 |
| 2020-12-28 00:00:00 |
FB |
BUY |
50 |
130 |
| 2020-12-29 00:00:00 |
FB |
SELL |
80 |
130 |
| 2020-12-30 00:00:00 |
FB |
SELL |
30 |
130 |
| 2020-12-31 00:00:00 |
FB |
BUY |
40 |
130 |
| 2020-11-16 00:00:00 |
AAPL |
BUY |
30 |
130 |
| 2020-11-17 00:00:00 |
AAPL |
SELL |
70 |
130 |
| 2020-11-20 00:00:00 |
AAPL |
BUY |
50 |
130 |
| 2020-11-24 00:00:00 |
AAPL |
BUY |
40 |
130 |
View on DB Fiddle
这篇文章对你学习窗口函数有帮助:An Intro to SQL Window Functions。
参考:
mysql window function with case