在连接3个表中使用左连接

时间:2018-10-25 09:22:34

标签: sql sql-server tsql join left-join

我有2个表,分别是Area_ Table和PingData_Table

  1. Area Table包含区域列表以及Area ID和Area Name
 AreaId | AreaName |  isActive
   1    |Jumbo House| 1
   2    | DCC       | 1
   3    |Dubai Mall | 1
  1. ping表具有由安装在具有不同ID的不同区域位置的设备进行的ping。我每5分钟ping每个设备一次,并更新表中的状态。
  

请注意,如果执行ping操作,则表中不会插入任何行   不成功,表示设备不活动

pkey  | AreaId  |   UpdatedOn
411   |   1     | 2018-08-08 21:54:24.810
547   |   1     | 2018-08-08 10:39:21.987
1046  |   1     | 2018-08-08 00:09:57.843

现在我要以以下格式显示以上数据。

2018年8月8日的设备状态

Areaid | Name           |   Status
1      |Jumbo House     | Active
2      |DCC             | Not Active between 00:00 hrs to 23:00 hrs
3      |Dubai Mall      | Not Active between XX:00 hrs to XX:00 hrs

所有区域。

到目前为止,我尝试过的是:

CREATE TABLE #TimeTable (hrs DATETIME)
CREATE TABLE #pingData (pid INT , areaId INT , pingTime DATETIME)
DECLARE 
  @start DATETIME = '2018-08-08 0:00', 
  @end   DATETIME =  '2018-08-08 23:00';
WITH x(n) AS 
(
  SELECT TOP (DATEDIFF(HOUR, @start, @end) + 1) 
  rn = ROW_NUMBER() OVER (ORDER BY [object_id]) 
  FROM sys.all_columns ORDER BY [object_id]
)
INSERT INTO #TimeTable(hrs) SELECT t = DATEADD(HOUR, n-1, @start) FROM x ORDER BY t;
INSERT INTO #pingData ( areaId  , pingTime ) 
SELECT DISTINCT [AreaId],CAST(FORMAT([UpdatedOn],'yyyy-MM-dd HH')+':00:00.000' as datetime) as pingtime 
FROM [dbo].[Pingtable] 
where UpdatedOn > @start and UpdatedOn <= @end
select  a.areaId , p.pingTime,t.hrs , a.AreaName , CASE WHEN  p.pingTime IS NULL THEN 'INACTIVE' ELSE 'ACTIVE' END as DeviceStatus
from Area_Table a   
left  join #pingData p on a.areaId = p.AreaId
left   join #TimeTable t  on p.pingTime = t.hrs 
ORDER BY a.areaId,t.hrs
drop table #TimeTable ;
drop table #pingData ;

请指导我如何获得所需的结果。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作

with ping as    
(
select AreaId,min(UpdatedOn) min_updatetime,
max(UpdatedOn) max_updatetime,
convert(date,UpdatedOn) as day_of_month
from ping_table
group by AreaId,convert(date,UpdatedOn)
) select A.AreaId,A.AreaName,
  case when P.AreaId is null then 'Not Active' else 'Active' end as Status
  from AreaTable A left join ping P  on A.AreaId=P.AreaId