[英]Calculate balance amount in redshift
CREATE TABLE inventory (
id SERIAL PRIMARY KEY,
stock_date DATE,
inbound_quantity INT,
outbound_quantity INT
);
INSERT INTO inventory
(stock_date, inbound_quantity, outbound_quantity
)
VALUES
('2020-01-01', '900', '0'),
('2020-01-02', '0', '300'),
('2020-01-03', '400', '250'),
('2020-01-04', '0', '100'),
('2020-01-05', '700', '500');
預計 Output :
庫存日期 | 入站數量 | 出站數量 | 平衡 |
---|---|---|---|
2020-01-01 | 900 | 0 | 900 |
2020-01-02 | 0 | 300 | 600 |
2020-01-03 | 400 | 250 | 750 |
2020-01-04 | 0 | 100 | 650 |
2020-01-05 | 700 | 500 | 850 |
詢問:
SELECT
iv.stock_date AS stock_date,
iv.inbound_quantity AS inbound_quantity,
iv.outbound_quantity AS outbound_quantity,
SUM(iv.inbound_quantity - iv.outbound_quantity) OVER (ORDER BY stock_date ASC) AS Balance
FROM inventory iv
GROUP BY 1,2,3
ORDER BY 1;
通過上面的查詢,我能夠計算 PostgresSQL 中的 in bound_quantity
和outbound_quantity
的余額。
但是,當我在Amazon-Redshift
中運行相同的查詢時,出現此錯誤:
Amazon Invalid operation: Aggregate window functions with an ORDER BY clause require a frame clause; 1 條聲明失敗。
我需要如何更改查詢才能使其在 Redshift 中也能正常工作?
正如錯誤所說,您需要添加框架規范子句,即ROWS UNBOUNDED PRECEDING
到您的 window function 中。
SELECT iv.stock_date AS stock_date,
iv.inbound_quantity AS inbound_quantity,
iv.outbound_quantity AS outbound_quantity,
SUM(iv.inbound_quantity - iv.outbound_quantity) OVER (
ORDER BY stock_date ASC
ROWS UNBOUNDED PRECEDING
) AS Balance
FROM inventory iv
GROUP BY 1,2,3
ORDER BY 1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.