如何找到今天的金额与上次在 SQL 中过帐交易的金额之间的差异?



我在SQL中有一个表,它有几个不同的产品。例如,该表包含 100 个产品,每个产品在表中都有一年中每天的一行。

某些金额为 NULL,因为当天没有报告任何数据,但该行仍然存在。为了给您一个表格示例,请参见下文:

ProductID / Date / Value
Product 1 / 2020-06-25 / 15.00
Product 1 / 2020-06-24 / 14.00
Product 1 / 2020-06-23 / 13.50
Product 1 / 2020-06-22 / NULL
Product 1 / 2020-06-21 / NULL
Product 1 / 2020-06-20 / 11.50
Product 2 / 2020-06-25 / 10.00
Product 2 / 2020-06-24 / 9.00
Product 2 / 2020-06-23 / 8.50
Product 2 / 2020-06-22 / 8.00
Product 2 / 2020-06-21 / 7.00
Product 2 / 2020-06-20 / 6.50

我正在尝试创建一个视图,该视图按天显示每个产品的变化率,并排除 NULL 值。视图应查找不是今天且值不为 null 的最新日期,然后将其与每个产品的当前金额进行比较。

换句话说,我希望视图显示以下内容:

a.ProductID / a.Date / a.Value / b.ProductID / b.Date / b.Value / ChangeinValue
Product 1 / 2020-06-25 / 15.00 / Product 1 / 2020-06-24 / 14.00 / 1.00
Product 1 / 2020-06-24 / 14.00 / Product 1 / 2020-06-23 / 13.50 / 0.50
*Product 1 / 2020-06-23 / 13.50 / Product 1 / 2020-06-20 / 11.50 / 2.00*
Product 2 / 2020-06-25 / 10.00 / Product 2 / 2020-06-24 / 9.00 / 1.00
Product 2 / 2020-06-24 / 9.00 / Product 2 / 2020-06-23 / 8.50 / 0.50
Product 2 / 2020-06-23 / 8.50 / Product 2 / 2020-06-22 / 8.00 / 0.50
Product 2 / 2020-06-22 / 8.00 / Product 2 / 2020-06-21 / 7.00 / 1.00
Product 2 / 2020-06-21 / 7.00 / Product 2 / 2020-06-20 / 6.50 / 0.50

在我如何创建此查询方面的任何帮助将不胜感激。

您可以使用窗口函数和一些过滤:

select *
from (
select
t.*,
lag(date)   over(partition by productID order by date) lag_date,
lag(value)  over(partition by productID order by date) lag_value,
value - lag(value) over(partition by productID order by date) change
from mytable t
where value is not null
) t
where lag_value is not null

最新更新