当前位置: 代码迷 >> Sql Server >> mssql存储过程或查询语句
  详细解决方案

mssql存储过程或查询语句

热度:85   发布时间:2016-04-24 20:02:24.0
求一个mssql存储过程或查询语句
表结构:
时间,  电表编号,度数,倍率
2013-9-11 04:50,0001,100,10
2013-9-11 03:30,0001,80,10 
2013-9-11 05:30, 0001, 105,10
2013-9-12 010:50,0001,120,10
2013-9-13 09:30,0001,180,10 
2013-9-14 10:30, 0001, 205,10
2013-9-11 04:50,0002,100,10
2013-9-11 03:30,0002,80,10 
2013-9-11 05:30, 0003, 105,10
2013-9-12 010:50,0003,120,10
2013-9-13 09:30,0003,180,10 
2013-9-14 10:30, 0003, 205,10
2013-9-11 05:30, 0005, 105,10
2013-9-12 010:50,0005,120,10
2013-9-13 09:30,0005,180,10 
2013-9-14 10:30, 0005, 205,10
怎么求出一段时间内每个电表编号的使用度数。
使用度数为选中时间段内的最后一个时间度数减去
第一个时间度数。
如果查询时间段位:9-1到10-1
则结果为

电表编号 使用度数
0001      105
0002      20 
0003      100
0005      100
求这个存储过程或查询怎么写?

------解决方案--------------------

create table #tab(时间 datetime,电表编号 varchar(50),度数 int ,倍率 int)
insert into #tab
select '2013-9-11 04:50',0001,100,10 union all
select '2013-9-11 03:30',0001,80,10  union all
select '2013-9-11 05:30', 0001,105,10 union all
select '2013-9-12 010:50',0001,120,10 union all
select '2013-9-13 09:30',0001,180,10  union all
select '2013-9-14 10:30', 0001, 205,10 union all
select '2013-9-11 04:50',0002,100,10 union all
select '2013-9-11 03:30',0002,80,10  union all
select '2013-9-11 05:30',0003,105,10 union all
select '2013-9-12 010:50',0003,120,10 union all
select '2013-9-13 09:30',0003,180,10  union all
select '2013-9-14 10:30',0003, 205,10 union all
select '2013-9-11 05:30',0005, 105,10 union all
select '2013-9-12 010:50',0005,120,10 union all
select '2013-9-13 09:30',0005,180,10  union all
select '2013-9-14 10:30', 0005, 205,10


select * from #tab


if OBJECT_ID('sp_test','p')is not null
drop proc sp_test
go
create proc sp_test
@starttime datetime,
@endtime datetime
as
begin
select 电表编号,sum(度数)度数 from #tab
where 时间 between @starttime and @endtime
group by 电表编号
end
go

exec sp_test'2013-9-1','2013-10-1'
----------------------------------------
电表编号                                               度数
-------------------------------------------------- -----------
1                                                  790
2                                                  180
3                                                  610
5                                                  610

(4 行受影响)


------解决方案--------------------

create table wg
(时间 varchar(20), 电表编号 varchar(10), 度数 int,倍率 int)

insert into wg
 select '2013-9-11 04:50', '0001', 100,10 union all
 select '2013-9-11 03:30', '0001', 80,10 union all
 select '2013-9-11 05:30', '0001', 105,10 union all
 select '2013-9-12 010:50', '0001', 120,10 union all
 select '2013-9-13 09:30', '0001', 180,10 union all
 select '2013-9-14 10:30', '0001', 205,10 union all
 select '2013-9-11 04:50', '0002', 100,10 union all
  相关解决方案