Oracle 使用类型和日期戳减去工作流表中的日期
我有一个包含3列的表:Oracle 使用类型和日期戳减去工作流表中的日期,oracle,sqlplus,Oracle,Sqlplus,我有一个包含3列的表: resid type date 该表用于跟踪工作流中的步骤,特定的resid可以存在多个具有不同类型id(编号)和日期戳的resid。 我想计算两次typeshift之间使用的时间,即在特定的resid上使用1和17 我已经尝试过这样的sql plus语法 并尝试使用别名: 有什么建议吗 select resid, date - date from tablename where resid, date in (select resid, da
resid type date
该表用于跟踪工作流中的步骤,特定的resid可以存在多个具有不同类型id(编号)和日期戳的resid。
我想计算两次typeshift之间使用的时间,即在特定的resid上使用1和17
我已经尝试过这样的sql plus语法
并尝试使用别名:
有什么建议吗
select resid, date - date
from tablename
where resid, date in
(select resid, date from tablename
where type='1')
and
where resid, date in
(select resid, date from tablename
where type='17')
and tablename.resid=tablename.resid
请不要将oracle保留字用作列名。
当(resid,type)是唯一的时,您可以执行以下操作:
SELECT :resid resid,
(select "date" FROM tablename WHERE resid = :resid AND "type" = '17') -
(select "date" FROM tablename WHERE resid = :resid AND "type" = '1') date_diff
FROM DUAL
您尝试的查询在中的
前面的列列表中缺少括号-因此应该是where(resid,date in)
-但也有无效的和where
,可能还有其他问题。大多数情况下,它并不能满足您的需要,尤其是因为两个date
值都来自同一行(对于类型1),所以减去它们总是得到零
您可以使用条件聚合:
select resid,
min(case when type_id = 17 then date_stamp end)
- min(case when type_id = 1 then date_stamp end) as diff
from tablename
where type_id in (1, 17) -- optional
and resid = :some_value
group by resid;
案例
为每个匹配行提供null或日期戳;然后,聚合将为您提供这些值中的单个值(支持非空值)
如果只有一个类型ID存在,那么差异将为null
如果可能存在倍数,您可能需要将17的min()
更改为max()
,这取决于您真正需要的
快速演示:
with tablename(resid, type_id, date_stamp) as (
select 1, 1, sysdate - 10 from dual
union all select 1, 17, sysdate - 7 from dual
union all select 2, 1, sysdate - 5 from dual
union all select 2, 17, sysdate - 3 from dual
union all select 3, 1, sysdate - 10 from dual
)
select resid,
min(case when type_id = 17 then date_stamp end)
- min(case when type_id = 1 then date_stamp end) as diff
from tablename
where type_id in (1, 17) -- optional
--and resid = 2
group by resid;
RESID DIFF
---------- ----------
1 3
2 2
3
对于每个resid
,类型1和类型17中是否只有一个;每个人都会有一个吗?如果没有(比如说1型存在,但17型还没有,或者有两个17型),它应该显示什么?样本数据和预期输出会有帮助。问题是什么?请显示示例数据或错误消息
with tablename(resid, type_id, date_stamp) as (
select 1, 1, sysdate - 10 from dual
union all select 1, 17, sysdate - 7 from dual
union all select 2, 1, sysdate - 5 from dual
union all select 2, 17, sysdate - 3 from dual
union all select 3, 1, sysdate - 10 from dual
)
select resid,
min(case when type_id = 17 then date_stamp end)
- min(case when type_id = 1 then date_stamp end) as diff
from tablename
where type_id in (1, 17) -- optional
--and resid = 2
group by resid;
RESID DIFF
---------- ----------
1 3
2 2
3