如何找到忽略空值的整数之间的差异
How to find difference between the integers ignoring null values
数据看起来像这样
Row CurrentPrice PriceChangeDate PreviousPrice
1 7.9 25/03/2022 null
2 null 25/03/2022 null
3 7.9 24/03/2022 null
4 8 01/03/2022 8.5
5 8.5 24/02/2022 8
预期输出
Row CurrentPrice PriceChangeDate PreviousPrice Difference
1 7.9 25/03/2022 7.9 0
2 7.9 24/03/2022 8 0.1
3 8 01/03/2022 8.5 0.5
4 8.5 24/02/2022 8 -0.5
我找不到获取预期数据的方法。
考虑以下方法
select *, round(PreviousPrice - CurrentPrice, 2) as Difference
from (
select * except(PreviousPrice),
ifnull(PreviousPrice, lag(CurrentPrice) over(order by PriceChangeDate)) as PreviousPrice
from your_table
where not CurrentPrice is null
)
如果应用于我们问题中的样本数据 - 输出是
根据您的要求,您可以使用 IFNULL conditional expressions to ignore the null values. You can try the code below where you can SAFE_CAST 值在 IFNULL 条件表达式中浮动。
SELECT * EXCEPT(PreviousPrice),
ifnull(SAFE_CAST(PreviousPrice AS FLOAT64),0) AS PreviousPrice,
ROUND(ifnull(SAFE_CAST(PreviousPrice AS FLOAT64),0) - ifnull(SAFE_CAST(CurrentPrice AS FLOAT64),0),2) AS Difference
FROM (
SELECT * EXCEPT(ROW,PreviousPrice),
ifnull(PreviousPrice,
LAG(CurrentPrice) OVER(ORDER BY PriceChangeDate)) AS PreviousPrice
FROM `project.dataset.pricechange`
WHERE NOT CurrentPrice = 'null'
ORDER BY PriceChangeDate DESC )
输出Table
数据看起来像这样
Row CurrentPrice PriceChangeDate PreviousPrice
1 7.9 25/03/2022 null
2 null 25/03/2022 null
3 7.9 24/03/2022 null
4 8 01/03/2022 8.5
5 8.5 24/02/2022 8
预期输出
Row CurrentPrice PriceChangeDate PreviousPrice Difference
1 7.9 25/03/2022 7.9 0
2 7.9 24/03/2022 8 0.1
3 8 01/03/2022 8.5 0.5
4 8.5 24/02/2022 8 -0.5
我找不到获取预期数据的方法。
考虑以下方法
select *, round(PreviousPrice - CurrentPrice, 2) as Difference
from (
select * except(PreviousPrice),
ifnull(PreviousPrice, lag(CurrentPrice) over(order by PriceChangeDate)) as PreviousPrice
from your_table
where not CurrentPrice is null
)
如果应用于我们问题中的样本数据 - 输出是
根据您的要求,您可以使用 IFNULL conditional expressions to ignore the null values. You can try the code below where you can SAFE_CAST 值在 IFNULL 条件表达式中浮动。
SELECT * EXCEPT(PreviousPrice),
ifnull(SAFE_CAST(PreviousPrice AS FLOAT64),0) AS PreviousPrice,
ROUND(ifnull(SAFE_CAST(PreviousPrice AS FLOAT64),0) - ifnull(SAFE_CAST(CurrentPrice AS FLOAT64),0),2) AS Difference
FROM (
SELECT * EXCEPT(ROW,PreviousPrice),
ifnull(PreviousPrice,
LAG(CurrentPrice) OVER(ORDER BY PriceChangeDate)) AS PreviousPrice
FROM `project.dataset.pricechange`
WHERE NOT CurrentPrice = 'null'
ORDER BY PriceChangeDate DESC )
输出Table