如何在我的桌子上找到离线经销商?

时间:2014-09-05 15:17:03

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

我在经销商表中有170个经销商。这些经销商每10秒向我的数据表发送一些数据。

我想找到在线和离线经销商。

如果经销商readTime> DATEADD(MINUTE,-30,GETDATE())经销商在线

如果经销商readTime< DATEADD(MINUTE,-30,GETDATE())经销商离线

我可以通过此查询找到在线经销商

         Select  D1.DeviceID, D1.readTime,DL.FirmName  

         from Data D1 with (nolock) 
         inner join Dealer as DL on DL.DeviceID=D1.DeviceID 
         where D1.OID   in 

             ( 

             select MAX (D2.OID) 
             from Data D2 with (nolock)
             where D2.readTime > DATEADD(MINUTE,-30,GETDATE()) and  
             D2.readTime<getdate()
             group by D2.DeviceID


             )   ORDER BY D1.readTime DESC

我尝试在第二次查询中找到离线经销商,但我遇到了这个问题:在线经销商在第二次查询时有数据。因为经销商每隔10秒发送一次数据。

如何才能找到离线经销商?

查询(更改&#39;&#39;到&#39;&gt;&#39;)

        Select  D1.DeviceID, D1.readTime,DL.FirmName  

         from Data D1 with (nolock) 
         inner join Dealer as DL on DL.DeviceID=D1.DeviceID 
         where D1.OID   in 

             ( 

             select MAX (D2.OID) 
             from Data D2 with (nolock)
             where D2.readTime > DATEADD(MINUTE,-30,GETDATE()) and  
             D2.readTime<getdate()
             group by D2.DeviceID


             )   ORDER BY D1.readTime DESC

2 个答案:

答案 0 :(得分:1)

由于您有一个子查询来定义 在线的人,并且您使用IN子句来查找这些子句,只需将该子句否定为NOT IN,类似的东西:

     Select  D1.DeviceID, D1.readTime,DL.FirmName  

     from Data D1 with (nolock) 
     inner join Dealer as DL on DL.DeviceID=D1.DeviceID 
     where D.OID   NOT in 

         ( 

         select MAX (D2.OID) 
         from Data D2 with (nolock)
         where D2.readTime > DATEADD(MINUTE,-30,GETDATE()) and  
         D2.readTime<getdate()
         group by D2.DeviceID


         )   ORDER BY D.readTime DESC

答案 1 :(得分:0)

解决。

   Select  D1.DeviceID, D1.readTime,DL.FirmName  

     from Data D1 with (nolock) 
     inner join Dealer as DL on DL.DeviceID=D1.DeviceID 
     where D1.OID   in 

         ( 

         select MAX (D2.OID) 
         from Data D2 with (nolock)
         where D2.readTime > DATEADD(MINUTE,-30,GETDATE()) and  
         D2.readTime<getdate()
         group by D2.DeviceID


         )  and   DATEDIFF(MINUTE,DATEADD(MINUTE,-30,GETDATE()),S.readTime)<0

             ORDER BY D1.readTime DESC