我正在使用SELECT postgres语句来创建具有特定条件的item_.amount列的滚动和。我希望滚动和字段具有以下标准。5天,卖出,A项10天,买,B 10天,卖出
我所做的工作如下:
首先,在数据库中,我有两个表:一个带有item_事务的表,一个带有日期字段的表。https://dbfiddle.uk/?rdbms=postgres_13&fiddle=80fcb5654ead862f7b057c76425e91ca
我已经把桌子合并到
select date_actual,transaction_date
FROM date LEFT JOIN item_ ON item_.transaction_date=date.date_actual
ORDER BY date.date_actual DESC我解释滚动栏(5天或10天)下面。我还需要考虑"A/B“的item_name和”买卖“的transaction_type。
例如,2021-4-10行的Rolling_A_sell_5day是76。76 + 0 +0+0+0上面的计算不包括94,因为它正在寻找"A“和"sell”列,所以它只包括76行,其余的行是0。

同样,对于第2021-4-10行中的Rolling_buy_10day也是94.0+0+0+ 94 +0+0+0+0+0+0+0

对于输出映像表,我尝试创建这样的SQL语句,但我不知道如何继续。
SELECT
t1.Id
,t1.transaction_date
,t1.amount
,SUM(t2.amount) as Rolling10DayQt
FROM item_ t1
CROSS JOIN(
SELECT *
FROM item_ a
WHERE a.id=t1.Id
AND (a.transaction_date > DATEADD(DAY,-10,t1.transaction_date) AND a.transaction_date <= t1.transaction_date) ) t2
GROUP BY t1.Id ,t1.transaction_date ,t1.amount输出表应该如下所示:

发布于 2021-04-29 03:21:04
我通过以下窗口语句和语句之间的范围解决了这个问题:
SUM((SELECT quantity as B_alloc
WHERE item_name='B')) OVER (
ORDER by date.date_actual
RANGE BETWEEN unbounded PRECEDING AND CURRENT ROW
) as CUM_inv_B,https://dbfiddle.uk/?rdbms=postgres_13&fiddle=c270837503bc96aa790d169bbe87d2bb
https://stackoverflow.com/questions/67068862
复制相似问题