【问题标题】:LAG function with sequential calculus具有顺序演算的 LAG 函数
【发布时间】:2021-03-30 18:05:32
【问题描述】:

我今天来找你是因为我在处理一个涉及 LAG 函数的查询(仅供参考,我使用的是 PostgreSQL)。 我有一张表格,其中包含按国家/地区每月向另一个国家销售的产品数量。该表是这样定义的:

create table market_research.test_tonnage(
    origin text, -- Origin country
    desti text, -- Destination country
    yr int, -- Year
    mt int, -- Month
    q numeric -- quantity sold (always > 0)
)

这是内容:

origin desti yr mt q
toto coucou 2019 1 1.4
toto coucou 2019 2 2.5
toto coucou 2019 3 1.2
tata yoyo 2018 11 5.4
tata yoyo 2018 12 5.5
tata yoyo 2019 1 5.2

我正在尝试创建一个将添加 2 个计算字段的视图,如下所示:

  • beginning_stock : 初始值为0,则beginning_stock = 上个月的ending_stock
  • ending_stock :ending_stock = begin_stock - q
origin desti yr mt q beginning_stock ending_stock
toto coucou 2019 1 1.4 0 -1.4
toto coucou 2019 2 2.5 -1.4 -3.9
toto coucou 2019 3 1.2 -3.9 -5.1
tata yoyo 2018 11 5.4 0 -5.4
tata yoyo 2018 12 5.5 -5.4 -10.9
tata yoyo 2019 1 5.2 -10.9 -16.1

我使用 LAG 函数尝试了许多查询,但我认为问题出在微积分随时间推移的顺序性上。这是我尝试的一个例子:

select origin,
       desti,
       yr,
       mt,
       q,
       COALESCE(lag(ending_stock, 1) over (partition by origin order by yr, mt), 0) beginning_stock,
       beginning_stock - q ending_stock    
 from market_research.test_tonnage

感谢您的帮助! 最大

【问题讨论】:

  • 向我们展示一些示例表数据和预期结果 - 作为格式化文本(无图像)。同时向我们展示您当前的查询尝试。 IE。 minimal reproducible example.
  • 你想要一个总和而不是滞后。
  • @jarlh 我已添加信息,希望对您有所帮助!

标签: sql postgresql lag sequential


【解决方案1】:

你需要一个累积的SUM()函数而不是LAG()

demo:db<>fiddle

SELECT
    *,
    SUM(-q) OVER (PARTITION BY origin ORDER BY yr, mt) + q as beginning, -- 2
    SUM(-q) OVER (PARTITION BY origin ORDER BY yr, mt) as ending         -- 1
FROM my_table
  1. 对所有数量求和(因为您想要负值,当然可以在之前将值设为负值),直到当前为您提供当前总数 (ending)
  2. 没有当前值的相同操作(再次添加q,因为SUM() 已经减去它)得到beginning

【讨论】:

  • 非常感谢您,先生,这是一个聪明的解决方案! :-)
猜你喜欢
  • 2016-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
  • 2020-09-04
  • 2022-01-18
相关资源
最近更新 更多