这是统计早上9点到10点开机的部分。
假设一个表结构如下
CREATE TABLE [dbo].[litestshebei](
[id] [int] NULL,
[shebeiid] [int] NULL,--设备编号
[shebeitime] [datetime] NULL,--时间
[shebeistate] [nvarchar](50) NULL--状态,1:开机;0:关机
) ON [PRIMARY]
根据表先建立一个视图
CREATE VIEW [dbo].[vlitestshebei]
AS
SELECT aa.shebeiid, aa.shebeitime, min(Expr3) AS shebeiclose
FROM (SELECT ROW_NUMBER() OVER (ORDER BY a.shebeiid, a.shebeitime, b.shebeitime) AS rn, a.id, a.shebeiid, a.shebeitime, a.shebeistate, b.id AS Expr1,
b.shebeiid AS Expr2, b.shebeitime AS Expr3, b.shebeistate AS Expr4
FROM (SELECT id, shebeiid, shebeitime, shebeistate
FROM CMICASE_Pub.dbo.litestshebei
WHERE (shebeistate = '1') AND (shebeitime <= '2016-01-01 10:00:00.000')) AS a LEFT OUTER JOIN
(SELECT id, shebeiid, shebeitime, shebeistate
FROM CMICASE_Pub.dbo.litestshebei
WHERE (shebeistate = '0') AND (shebeitime >= '2016-01-01 9:00:00.000')) AS b ON a.shebeiid = b.shebeiid AND a.shebeitime <= b.shebeitime) AS aa
GROUP BY aa.shebeiid, aa.shebeitime
GO
然后继续
select aaa.[shebeiid],SUM(mm) as 开机时间
from(
select aa.[shebeiid],datediff(minute,[shebeitime],[shebeiclose]) as mm
from
( select [shebeiid],
CASE WHEN [shebeitime]<'2016-01-01 09:00:00.000' THEN '2016-01-01 09:00:00.000'
else [shebeitime]
end as 'shebeitime',
CASE WHEN [shebeiclose]<='2016-01-01 10:00:00.000' THEN [shebeiclose]
else '2016-01-01 10:00:00.000'
end as 'shebeiclose'
from [CMICASE_Pub].[dbo].[vlitestshebei]
) as aa
) as aaa group by [shebeiid]
这样就显示不同设备9点到10点开机时间了。
如果不清楚,把你的表的数据结构发上来,我按照你的表重新写一个。