将结果集格式化为所需格式时出现问题

时间:2018-10-26 07:26:49

标签: sql sql-server tsql formatting

我的设备安装在具有不同区域ID的其他位置,我每小时以以下格式返回不同区域的设备活动状态。

AreaId  |   UpdatedOn             | DeviceStatus
  1     | 2018-08-08 00:00:00.000 | Active
  1     | 2018-08-08 01:00:00.000 | Active
  1     | 2018-08-08 02:00:00.000 | Active
  2     | 2018-08-08 00:00:00.000 | Inactive
  2     | 2018-08-08 01:00:00.000 | Active
  2     | 2018-08-08 02:00:00.000 | Active
  3     | 2018-08-08 00:00:00.000 | Active
  3     | 2018-08-08 01:00:00.000 | Inactive
  3     | 2018-08-08 02:00:00.000 | Inactive

清楚可见,设备1始终处于活动状态。设备2在00.00到01.00小时之间处于非活动状态 并且设备3从01.00到02.00以及从02.00到03.00小时处于非活动状态。

我想以以下格式显示此数据。

2018年8月8日0:00至03:00的设备状态

Areaid     | Status
1          | Active
2          | Not Active between 00:00 hrs to 01:00 hrs
3          | Not Active between 01:00 hrs to 02:00 hrs and  02:00 hrs to 03:00 hrs

所有区域。

我该如何实现?

2 个答案:

答案 0 :(得分:2)

您可以尝试在子查询中使用STUFF函数来获取DeviceStatus = 'Inactive'行数据,然后基于outer join表获取AreaId

SELECT t2.AreaId, coalesce(Status,'Active') Status
FROM (
    SELECT distinct AreaId,DeviceStatus,
           STUFF((
             SELECT ' and ' + CONVERT(VARCHAR(5),UpdatedOn,108) + ' hrs' + ' to ' + CONVERT(VARCHAR(5),DATEADD(HOUR,1,UpdatedOn),108) + ' hrs'
             FROM T tt
             WHERE tt.AreaId = t1.AreaId and tt.DeviceStatus =  t1.DeviceStatus
             FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
           ,1,4,'') Status

    FROM T t1
    WHERE DeviceStatus = 'Inactive'
) t1 RIGHT JOIN 
(
    SELECT distinct AreaId
    FROM T
) t2
on t1.AreaId = t2.AreaId 

sqlfiddle

结果

AreaId  Status
1      Active
2      00:00 hrs to 01:00 hrs
3      01:00 hrs to 02:00 hrs and 02:00 hrs to 03:00 hrs

答案 1 :(得分:0)

您可以在下面使用lag()函数尝试

DEMO

select id,concat('Not Active between ', format(cast(prevd as datetime),' hh:mm '), 'hrs to ', format(cast(d as datetime),' hh:mm '), 'hrs') from
(select *,
LAG (d, 1, 0) OVER (PARTITION BY id ORDER BY d) prevd,
LAG (p, 1, 0) OVER (PARTITION BY id ORDER BY d) prevp
from cte1 
)a where prevp<>'0' and p<>prevp

输出:

id  status
1   Not Active between  01:00 hrs to  02:00 hrs
2   Not Active between  01:00 hrs to  02:00 hrs