您需要在查询中添加分组依据:
select a.account_id, a.transaction_id, min(time_between) as min_time_between
from (select a.account_id, a.transaction_id, b.transaction_date, a.transaction_date,
round(a.transaction_date - b.transaction_date, 0) as Time_between
from time_between_trans a join
time_between_trans b
on a.transaction_date > b.transaction_date and
a.account_ID ='717724' and
a.account_id = b.account_id
) a
group by a.account_id, a.transaction_id
我还修复了您的连接语法以使用正确的连接语法,并将“like”更改为“=”,因为您没有通配符。
可能有其他方法来表达这一点,但这是标准 SQL。您应该指定您在问题中使用的数据库。
如果您使用的是 Oracle,那么只需执行以下操作:
select a.*,
(case when nextdt - transaction_date) < transaction_date - nextdt
then nextdt - transaction_date)
else transaction_date - nextdt
end) as mintime
from (select a.*,
lead(transaction_date, 1) over (partition by account_id order by transaction_date) as nexttd,
lag(transaction_date, 1) over (partition by account_id order by transaction_date) as prevtd
from time_between_trans a
) a
实际上,这并不完全正确,因为对于 nexttd 和 prevtd,您必须考虑 NULL。但是,这个想法很简单。领先和滞后功能让您可以进行 prev 或 text 交易,然后您可以做任何您想做的事情来找到最小值——或者从记录中获取您想要的任何其他信息。