我有一个应用程序,用户可以在其中创建存储在Oracle数据库中的订单。我试图找到一个只有当用户在他们创建的最后一个订单的30秒内创建订单时才会发生的错误。
以下是订单表的结构:
order_id | user_id | creation_date
我想写一个查询,它可以给我一个订单列表,其中creation_date在同一用户的最后一个订单的30秒内。结果将有助于我找到错误。
我尝试使用Oracle LAG()函数,但似乎没有使用WHERE子句。
有什么想法?
答案 0 :(得分:2)
SELECT O.*
FROM YourTable O
WHERE EXISTS (
SELECT *
FROM YourTable O2
WHERE
O.creation_date > O2.creation_date
AND O.user_id = O2.user_id
AND O.creation_date - (30 / 86400) <= O2.creation_date
);
在行动in a Sql Fiddle中查看此内容。
如果需要,可以使用LAG
函数,只需将查询包装到派生表中,然后将WHERE
条件放在外部查询中。
答案 1 :(得分:0)
SELECT distinct
t1.order_id, t1.user_id, t1.creation_date
FROM
YourTable t1
join YourTable t2
on t2.user_id = t1.user_id
and t2.creation_date between t1.creation_date - 30/86400 and t1.creation_date
and t2.rowid <> t1.rowid
order by 3 desc
答案 2 :(得分:0)
使用LAG()的示例:
SELECT id, (pss - css) time_diff_in_seconds
, creation_date, prev_date
FROM
(
SELECT id, creation_date, prev_date
, EXTRACT(SECOND From creation_date) css
, EXTRACT(SECOND From prev_date) pss
FROM
(
SELECT id, creation_date
, LAG(creation_date, 1, creation_date) OVER (ORDER BY creation_date) prev_date
FROM
( -- Table/data --
SELECT 1 id, timestamp '2013-03-20 13:56:58' creation_date FROM dual
UNION ALL
SELECT 2, timestamp '2013-03-20 13:57:27' FROM dual
UNION ALL
SELECT 3, timestamp '2013-03-20 13:59:16' FROM dual
)))
--WHERE (pss - css) <= 30
/
ID TIME_DIFF_IN_SECONDS
--------------------------
1 0 <<-- if uncomment where
2 31
3 11 <<-- if uncomment where