【问题标题】:How to retrieve difference in value between a value of the current and previous rows without using temp table?如何在不使用临时表的情况下检索当前行和先前行的值之间的值差异?
【发布时间】:2021-04-13 11:05:41
【问题描述】:

我想检索当前行和之前行的值在 Counter 列(以下是示例数据)中的差异。

所以第一列将是计数器,第二列将是当前行计数器和前一个计数器的差异。这是一个例子:

我想写这样的东西:

select 
  id,
  counter - LAG(counter, 1) OVER (ORDER BY counter)
from table

这是我的查询结果: 我正在使用 Google Bigquery。

【问题讨论】:

  • 为什么id 在所有行中都相同?您的查询有什么问题?
  • 有几个ID。那是一个样本输出。我现在将添加一个示例输出

标签: sql select google-bigquery


【解决方案1】:

如果您的计数器从不减少并且您希望得到每个id 的结果,那么您就在正确的轨道上。我想你想要:

select id, counter,
       counter - lag(counter) over (partition by id order by counter) as diff
from table
order by id, counter;

注意:这包括 id 作为第一列,因为它似乎相关。

【讨论】:

  • 非常感谢,我添加到 Lag 的 1 似乎改变了答案。您的解决方案有效。再次感谢你。我会尽快接受答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
相关资源
最近更新 更多