34,576
社区成员
发帖
与我相关
我的任务
分享
with a_tmp as (
select time,value,row_number( ) over ( order by time) num from a_test --a_test 是数据表
)
select c1.time, isnull(c1.value -c2.value,0) from a_tmp c1 left join a_tmp c2 on c1.num = c2.num+1
order by c1.time
if not object_id('tb1') is null
drop table tb1
go
create table tb1(id int, time datetime, value int)
go
--电表读数应该有一个初始值,所以这里多加了一条记录,不然第一条记录统计不到用电量
insert into tb1(id, time, value)
select 5, '2017-05-31 00:00', 10 union all
select 1, '2017-05-31 01:00', 10 union all
select 2, '2017-05-31 03:00', 16 union all
select 3, '2017-05-31 02:00', 14 union all
select 4, '2017-05-31 04:00', 19
--考虑到电表抄表可能1小时不只一条记录,或者某些小时没有抄表记录,所以拿用电量来累计
--按抄表时间重新排序并计算每段时间的用电量,分组汇总
--实际情况会有多个电表,你自己再加一个统计条件
;with ctetb( idnew, id, time ,value)
as
(
select row_number() over(order by time) as idnew, id, time , value
from tb1
)
select convert(varchar(13) , time2, 121) counttime, sum(amount) amount
from (
select
c.idnew idnew1, d.idnew idnew2, c.time time1, d.time time2 ,c.value value1, d.value value2, (d.value-c.value) as amount
from
ctetb c
join ctetb d
on c.idnew=d.idnew-1
) a
group by convert(varchar(13) , time2, 121)
order by convert(varchar(13) , time2, 121)
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([ID] int,[Time] NVARCHAR(100),[Value] int)
Insert #T
select 1,'2017-05-31 01:00',10 union all
select 2,'2017-05-31 03:00',16 union all
select 3,'2017-05-31 02:00',14 union all
select 4,'2017-05-31 04:00',19
Go
--测试数据结束
SELECT a.Time ,
ISNULL(a.Value - b.Value,0) AS Value
FROM #T a
LEFT JOIN #T b ON DATEDIFF(HOUR, CONVERT(DATETIME, b.Time),
CONVERT(DATETIME, a.Time)) = 1
ORDER BY a.Time
SELECT *,value-ISNULL(LAG(Value)OVER(ORDER BY Time),Value) FROM #t
ID Time Value
----------- ---------------------------------------------------------------------------------------------------- ----------- -----------
1 2017-05-31 01:00 10 0
3 2017-05-31 02:00 14 4
2 2017-05-31 03:00 16 2
4 2017-05-31 04:00 19 3
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([ID] int,[Time] NVARCHAR(100),[Value] int)
Insert #T
select 1,'2017-05-31 01:00',10 union all
select 2,'2017-05-31 03:00',16 union all
select 3,'2017-05-31 02:00',14 union all
select 4,'2017-05-31 04:00',19
Go
--测试数据结束
SELECT a.Time ,
ISNULL(a.Value - b.Value,0) AS Value
FROM #T a
LEFT JOIN #T b ON DATEDIFF(HOUR, CONVERT(DATETIME, b.Time),
CONVERT(DATETIME, a.Time)) = 1