Sql 以最小时差获取记录
我有一个要求,我需要得到一个记录与当前记录的最小时差。 让我们假设在一个表中有insert date、group Id和Id列。 我已选择了一条记录,不想获取另一条记录,因为所选记录的插入日期和另一条记录之间的差异最小 我已经尝试了外部应用,但该查询需要永远运行 查询:Sql 以最小时差获取记录,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有一个要求,我需要得到一个记录与当前记录的最小时差。 让我们假设在一个表中有insert date、group Id和Id列。 我已选择了一条记录,不想获取另一条记录,因为所选记录的插入日期和另一条记录之间的差异最小 我已经尝试了外部应用,但该查询需要永远运行 查询: select e.id from B.Emp t where id = 5 outer apply ( select top 1 * from B.Emp where t.group_id = grou
select e.id
from B.Emp t
where id = 5
outer apply (
select top 1 *
from B.Emp
where t.group_id = group_id
order by insert_time desc ) e
此查询未经测试。
如果查询中有任何错误或更改,请回复我
CREATE TABLE Emp
(
group_Id INT,
ID INT,
date DATETIME
)
INSERT INTO EMP
(group_Id,ID,date)
values
(1,5,'11-Jan-2014'),
(1,5,'12-Jan-2014')
--
尝试第二种方法。如果您确实希望为所选记录组找到最接近的插入时间,而不考虑方向,那么类似的方法可能会有所帮助:
select t.insert_date, ca.*
from B.Emp t
outer apply (
select top (1) * from B.Emp e
where e.group_id = t.group_id
and e.id != t.id
order by abs(datediff(ms, t.insert_date, e.insert_date))
) ca
where t.Id = 5;
编辑:不过,您肯定需要检查索引选项。对于初学者,假设您在Id
列上有一个集群主键,这将有助于:
create index [IX_B_Emp_GroupInsert] on B.Emp (group_id, insert_time);
@多同步我只是想给出一个想法。我希望这能起作用这是我尝试过的,但表中有数百万条记录,所以查询永远在运行,不会产生结果。@vinodsahu,你们看过执行计划了吗?该表建议使用哪些指数?作为一个粗略的猜测,我可能会从
(组id,插入日期)
开始。我不是sql专家,但我的一个队友尝试了索引,在执行计划中,它显示outer apply将检查所有记录我尝试了这个,但结果显示了该组id的所有记录,包括id 5。让我看看问题。你能分享一些样本数据吗?
select t.insert_date, ca.*
from B.Emp t
outer apply (
select top (1) * from B.Emp e
where e.group_id = t.group_id
and e.id != t.id
order by abs(datediff(ms, t.insert_date, e.insert_date))
) ca
where t.Id = 5;
create index [IX_B_Emp_GroupInsert] on B.Emp (group_id, insert_time);