将记录关联在一起

时间:2014-09-23 05:34:12

标签: sql sql-server sql-server-2008

我在表格中存储了以下数据。

DateCreated              ServerName  Heading
2014-09-23 13:43:31.477 LAB1\TEST SQL Server status: Unable To Connect
2014-09-23 13:30:23.017 LAB1\TEST SQL Server running
2014-09-23 13:26:21.110 LAB1\TEST SQL Server status: Unable To Connect
2014-09-23 13:20:42.243 LAB1\TEST SQL Server running
2014-09-23 13:16:30.457 LAB1\TEST SQL Server status: Unable To Connect
2014-09-23 13:15:03.993 LAB1\TEST SQL Server running
2014-09-23 13:08:36.763 LAB1\TEST SQL Server status: Unable To Connect
2014-09-23 13:05:59.490 LAB1\TEST SQL Server running
2014-09-23 12:59:30.017 LAB1\TEST SQL Server status: Unable To Connect
2014-09-23 12:55:49.303 LAB1\TEST SQL Server running
2014-09-23 09:54:43.180 LAB1\TEST SQL Server status: Unable To Connect
2014-09-23 09:52:05.453 LAB1\TEST SQL Server running
2014-09-23 09:46:55.013 LAB1\TEST SQL Server status: Unable To Connect
2014-09-23 09:44:54.957 LAB1\TEST SQL Server running
2014-09-23 09:11:24.100 LAB1\TEST SQL Server status: Unable To Connect
2014-09-23 09:06:55.703 LAB1\TEST SQL Server running
2014-09-23 08:59:53.773 LAB1\TEST SQL Server status: Unable To Connect
2014-09-23 07:55:35.537 LAB1\TEST SQL Server running
2014-09-23 07:49:50.830 LAB1\TEST SQL Server status: Unable To Connect


我需要将所有“无法连接”记录与相应的“SQL Server运行”记录相关联,并计算出每个记录之间的持续时间。

它需要考虑到可能没有“SQL Server运行”记录,如上面的例子“2014-09-23 13:43:31.477”,这意味着它仍然是关闭的。

有没有人对我如何处理这个有任何建议?

1 个答案:

答案 0 :(得分:0)

选择所有连接失败记录。对于每个节目,下一个(即最小的)连接时间。

select 
  datecreated, 
  servername,
  (
    select min(running.datecreated)
    from mytable running
    where running.heading = 'SQL Server running'
    and running.servername = notrunning.servername
    and running.datecreated > notrunning.datecreated
  ) as connected
from mytable notrunning
where heading = 'SQL Server status: Unable To Connect';

基于此,您可以计算持续时间。请注意,您可能会因一次连接而尝试多次尝试失败。您可以考虑仅显示每个连接的第一次失败,并忽略其他连接。但这需要更复杂的查询。 (或者你的表只存储了第一次失败吗?那么你已经得到了所需的东西。)