【发布时间】:2023-01-18 15:56:41
【问题描述】:
CREATE TABLE inventory (
id SERIAL PRIMARY KEY,
stock_date DATE,
product VARCHAR(255),
inbound_quantity INT,
outbound_quantity INT
);
INSERT INTO inventory
(stock_date, product, inbound_quantity, outbound_quantity
)
VALUES
('2020-01-01', 'Product_A', '900', '0'),
('2020-01-02', 'Product_A', '0', '300'),
('2020-01-03', 'Product_A', '400', '250'),
('2020-01-04', 'Product_A', '0', '100'),
('2020-01-05', 'Product_A', '700', '500'),
('2020-01-03', 'Product_B', '850', '0'),
('2020-01-08', 'Product_B', '100', '120'),
('2020-02-20', 'Product_B', '0', '360'),
('2020-02-25', 'Product_B', '410', '230'),
预期结果:
| stock_date | product | inbound_quantity | outbound_quantity | balance |
|---|---|---|---|---|
| 2020-01-01 | Product_A | 900 | 0 | 900 |
| 2020-01-02 | Product_A | 0 | 300 | 600 |
| 2020-01-03 | Product_A | 400 | 250 | 750 |
| 2020-01-04 | Product_A | 0 | 100 | 650 |
| 2020-01-05 | Product_A | 700 | 500 | 850 |
| 2020-01-03 | Product_B | 740 | 0 | 740 |
| 2020-01-08 | Product_B | 100 | 120 | 720 |
| 2020-02-20 | Product_B | 0 | 360 | 360 |
| 2020-02-25 | Product_B | 410 | 230 | 540 |
| 2020-03-09 | Product_B | 290 | 0 | 830 |
我想计算每个产品的余额。
到目前为止,我已经能够在下面开发这个查询,但它不起作用。
我收到错误 window "product" does not exist。
SELECT
iv.stock_date AS stock_date,
iv.product AS product,
iv.inbound_quantity AS inbound_quantity,
iv.outbound_quantity AS outbound_quantity,
SUM(iv.inbound_quantity - iv.outbound_quantity) OVER
(product ORDER BY stock_date ASC ROWS UNBOUNDED PRECEDING) AS Balance
FROM inventory iv
GROUP BY 1,2,3,4
ORDER BY 2,1;
我需要如何修改查询才能使其工作?
【问题讨论】:
标签: sql postgresql