24小时每小时的百分比汇总

时间:2017-07-18 16:27:12

标签: sql sql-server tsql

使用SQL Server 2008 R2。

我试图获得每小时分解24小时的上升时间百分比。

如果列AlertID为1,则表示系统已启动。如果AlertID是其他任何数字,那么它被认为是失败的。

以下是我目前无法正常工作且效果不佳的问题,但让我们先让它发挥作用。 UpTime列始终为0.

 SELECT a.dayhour,
       ( (SELECT Count(*)
          FROM   commandhistory
          WHERE  commandid = '4263745C-5603-4E3D-AFB2-CA0E27969D0B'
                 AND alertid = 1
                 AND Datepart(hour, recordeddttm) = a.dayhour * 100) / (SELECT
         Count(*) FROM commandhistory
         WHERE commandid = '4263745C-5603-4E3D-AFB2-CA0E27969D0B'
           AND Datepart(hour, recordeddttm) = a.dayhour) ) AS UpTime
FROM   (SELECT 0 AS DayHour UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12 UNION SELECT 13 UNION SELECT 14 UNION SELECT 15 UNION SELECT 16 UNION SELECT 17 UNION SELECT 18 UNION SELECT 19 UNION SELECT 20 UNION SELECT 21 UNION SELECT 22 UNION SELECT 23) a
       LEFT JOIN commandhistory h
              ON a.dayhour = Datepart(hour, recordeddttm)
GROUP  BY a.dayhour
ORDER  BY a.dayhour  

示例表:(还有其他数据,但我不关心此实例)

uniqueidentifier CommandID
smallint         AlertID
datetime         RecordedDTTM

AlertID可以是1-5。 1意味着它,任何其他数字应该被视为向下。

1 个答案:

答案 0 :(得分:1)

怎么样:

;with cte as
(
SELECT Datepart(hour, recordeddttm) as DayHour
    , sum(case when alertID=1 then 1 else 0 end) as UpTimeCt
    , sum(case when alertID <> 1 then 1 else 0 end) as DownTimeCt
    , Count(*) AllCt
FROM   commandhistory
WHERE  commandid = '4263745C-5603-4E3D-AFB2-CA0E27969D0B'
--AND cast(recordeddttm as date) = [some date] --This is optional but limits data set
group by Datepart(hour, recordeddttm)
)

select DayHour
   , UpTimeCt
   , UpTimeRate = UpTimeCt/AllCt --AllCt might need to be cast
   , DownTimeCt
   , DownTimeRate = DownTimeCt / AllCt --AllCt might need to be cast
from cte