存储过程如下:
USE ShanghaiWorld
GO
/****** Object: StoredProcedure [dbo].[GetGroupDataStat] Script Date: 2012/10/10 8:52:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[GetGroupDataStat]
-- Add the parameters for the stored procedure here
@GroupId nvarchar(50), --集团ID
@YearStat int, --统计年份
@MonthStat int, --统计月份
@StatLastDate decimal(12, 2) = 1 output, --去年同期使用量
@StatYearData decimal(12, 2) = 1 output --今年使用量
AS
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
declare @StatMonth decimal(12, 2) = 0 --当前使用量
declare @LastYear int --去年的年份
set @LastYear = @YearStat - 1
declare @tmpMetaID table --临时表,存放设备信息
(
[id] int IDENTITY(1,1),
[MetaID] nvarchar(50),
[StartTime] datetime,
[EndTime] datetime null
)
--获取所有设备及其使用时间(大于上一年)
insert into @tmpMetaID select a.MetaID, a.StartTime, a.EndTime from TenantMetaMapping a
inner join GroupTenantMapping b on a.TenantID = b.TenantID
where DATEPART(year, a.StartTime) >= @LastYear and DATEPART(month, a.StartTime) >= 1 and b.GroupID = @GroupId
declare @tmpMaxID int --临时表的记录条数
select @tmpMaxID = MAX(id) from @tmpMetaID
declare @MetaID nvarchar(50)
declare @StartTime datetime
declare @EndTime datetime
while @tmpMaxID > 0
begin
select @MetaID = [MetaID], @StartTime = [StartTime], @EndTime = [EndTime] from @tmpMetaID where [id] = @tmpMaxID
declare @tmpValue decimal(12, 2)
if @EndTime is not null
begin
select @tmpValue = SUM(MeasureValue) from ElecData where MetaID = @MetaID and DATEPART(year, ReadTime) = @YearStat and ReadTime > @StartTime and ReadTime < @EndTime --今年使用量
if @tmpValue is not null set @StatYearData = @StatYearData + @tmpValue
select @tmpValue = SUM(MeasureValue) from ElecData where MetaID = @MetaID and DATEPART(year, ReadTime) = @YearStat and DATEPART(month, ReadTime) = @MonthStat and ReadTime > @StartTime and ReadTime < @EndTime --当前使用量
if @tmpValue is not null set @StatMonth = @StatMonth + @tmpValue
select @tmpValue = SUM(MeasureValue) from ElecData where MetaID = @MetaID and DATEPART(year, ReadTime) = @LastYear and DATEPART(month, ReadTime) = @MonthStat and ReadTime > @StartTime and ReadTime < @EndTime --去年同期