在下表示例 - 表A中,我们有四个不同ID 1,2,3,4的条目,分别具有相应的状态和时间。我想找到" ID"花了最多的时间来改变"状态"从开始到完成。在下面的示例中,它是ID = 4.我想运行查询并查找结果,我们目前在表中有大约百万条记录。如果有人提供有效的方法来检索这些数据,那将是非常好的。
表A
ID Status Date(YYYY-DD-MM HH:MM:SS)
1. Started 2017-01-01 01:00:00
1. Completed 2017-01-01 02:00:00
2. Started 2017-10-02 03:00:00
2. Completed 2017-10-02 05:00:00
3. Started 2017-15-03 06:00:00
3. Completed 2017-15-03 09:00:00
4. Started 2017-22-04 10:00:00
4. Completed 2017-22-04 15:00:00
谢谢! 布鲁斯
答案 0 :(得分:0)
我没有运行此sql,但它可以解决您的问题。
select a.id, max(DATEDIFF(SECOND, a.date, b.date + 1)) from TableA as a
join TableA as b on a.id = b.id
where a.status="started" and b.status="completed"
答案 1 :(得分:0)
SELECT
started.ID, timediff(completed.date, started.date) as elapsed_time
FROM TABLE_A as started
INNER JOIN TABLE_A as completed ON (completed.ID=started.ID AND completed.status='Completed')
WHERE started.status='Started'
ORDER BY elapsed_time desc
确保TABLE_A上有列ID,日期
的索引答案 2 :(得分:0)
您可以查询如下:
Select top 1 with ties Id from #yourDate y1
join #yourDate y2
On y1.Id = y2.Id
and y1.[STatus] = 'Started'
and y2.[STatus] = 'Completed'
order by Row_number() over(order by datediff(mi,y1.[Date], y2.[date]) desc)
答案 3 :(得分:0)
这是一种使用相关子查询的方法。在这种情况下,只需取消注释TOP 1
即可获得ID 4。这是基于你的评论,只有1"开始"记录,但可以是多个"完成"每个ID的记录。
declare @TableA table (ID int, Status varchar(64), Date datetime)
insert into @TableA
values
(1,'Started','2017-01-01 01:00:00'),
(1,'Completed','2017-01-01 02:00:00'),
(2,'Started','2017-02-10 03:00:00'),
(2,'Completed','2017-02-10 05:00:00'),
(3,'Started','2017-03-15 06:00:00'),
(3,'Completed','2017-03-15 09:00:00'),
(4,'Started','2017-04-22 10:00:00'),
(4,'Completed','2017-04-22 15:00:00')
select --top 1
s.ID
,datediff(minute,s.Date,e.EndDate) as TimeDifference
from @TableA s
inner join(
select
ID
,max(Date) as EndDate
from @TableA
where Status = 'Completed'
group by ID) e on e.ID = s.ID
where
s.Status = 'Started'
order by
datediff(minute,s.Date,e.EndDate) desc
<强>返回强>
+----+----------------+
| ID | TimeDifference |
+----+----------------+
| 4 | 300 |
| 3 | 180 |
| 2 | 120 |
| 1 | 60 |
+----+----------------+
答案 4 :(得分:0)
如果你知道&#39;已经开始&#39;永远是每个ID最早的时间点,也是最后一个完成的ID#39;您正在考虑的记录将始终是每个ID的最新时间点,以下应该对大量记录具有良好的性能:
SELECT TOP 1
id
, DATEDIFF(s, MIN([Date]), MAX([date])) AS Elapsed
FROM @TableA
GROUP BY ID
ORDER BY DATEDIFF(s, MIN([Date]), MAX([date])) DESC