我有一个这样的Oracle表:
Serial Some_value Date(Date Field type)
1 100 4-10-2019 8:00
1 106 4-17-2019 7:00
2 100 4-10-2019 8:00
2 101 4-17-2019 6:33
3 100 4-10-2019 9:00
3 110 4-17-2019 6:00
我想查询一个返回序列号的查询,该序列号在当前读数和7天后之间的差异大于5。上面的示例表的输出将如下所示:
Serial Difference
1 6
3 10
我目前有此SQL来获取现值和7天前的值,但我一直在努力将它们拼凑在一起。
(select quantity from Parts where date > sysdate-1) -
(select quantity from Parts where to_char(sysdate-7,'DDD') =
to_char(date,'DDD') and
to_char(sysdate-7,'YYYY') = to_char(date,'YYYY') and
to_char(sysdate-7,'MM') = to_char(date,'MM'))
谢谢!
答案 0 :(得分:0)
我们可以在此处尝试使用LAG
函数:
WITH cte AS (
SELECT Serial, Some_value, "Date",
LAG(Some_value, 1) OVER (PARTITION BY Serial ORDER BY "Date") Some_value_lag
FROM Parts
)
SELECT
Serial,
"Date",
ABS(Some_value - Some_value_lag) AS difference
FROM cte
WHERE
ABS(Some_value - Some_value_lag) > 5
ORDER BY
Serial,
"Date";
上面的CTE首先在每个串行记录组中按日期生成Some_value
列的滞后。然后,我们查询仅包含某些值之间的绝对差值超过5的记录。请注意,每个串行组中的最早记录将不会自动包含在结果集中,因为LAG
将返回{{1 }} 在这种情况下。我继续将日期包括在输出中,因为它更易于阅读。
答案 1 :(得分:0)
您可以按照以下方式进行操作:
select *
from (
select serial,
min(case when trunc(date_) = trunc(sysdate) then quantity end)
- min(case when trunc(date_) = trunc(sysdate - 7) then quantity end) diff
from parts
where trunc(date_) in (trunc(sysdate), trunc(sysdate-7))
group by serial)
where diff > 5
或如果不需要子查询,请使用having
子句。