基于logtime的Diff bw列

时间:2013-02-25 10:48:26

标签: sql-server-2008 sum calculated-columns

我的表是:

Logtime              Energy
-------------------  --------
2013-02-22 15:30:00  36883.79
2013-02-21 17:30:00  36767.68
2013-02-20 17:30:00  35447.97
2013-02-19 17:30:00  34170.04
2013-02-18 15:30:00  32663.54
2013-02-15 17:30:00  31649.39
2013-02-13 17:30:00  29091.99
2013-02-12 17:30:00  27807.49

我需要获得两个logtime值之间的差异。

例如:

2013-02-18 15:30:002013-02-22 15:30:00之间的能量差异为4220.25

我试过这样:

declare @energy varchar(30)
declare @min int
declare @max int
declare @result varchar(30)
select Logtime,Energy from PLENE_EnergySum order by Logtime desc
set @min=cast((select min(Energy) as [Energy] from PLENE_EnergySum where Logtime between
 '2013-02-22 15:30:00' and  '2013-02-18 15:30:00')as int)
set @max=cast((select max(Energy) as [Energy] from PLENE_EnergySum where Logtime between
'2013-02-22 15:30:00' and  '2013-02-18 15:30:00')as int)
set @result=@max-@min
insert into weekreport values('Fourth',@result) 

我在weekreport表中得到空值

week    energy
------  ------
Fourth  NULL

1 个答案:

答案 0 :(得分:0)

set @ first = Cast(Year(getdate())as varchar(10))+' - '+ Cast(Month(getdate())as varchar(10))+' - '+'01'

设置@ st = Cast(Year(getdate())为varchar(10))+' - '+ Cast(Month(getdate())为varchar(10))+' - '+'08'

set @ st1 = Cast(Year(getdate())as varchar(10))+' - '+ Cast(Month(getdate())as varchar(10))+' - '+'15'

set @ st2 = Cast(Year(getdate())as varchar(10))+' - '+ Cast(Month(getdate())as varchar(10))+' - '+'22'

set @ st3 = Cast(Year(getdate())as varchar(10))+' - '+ Cast(Month(getdate())as varchar(10))+' - '+'32'

设置@ min =(从PLENE_EnergySum中选择min(Energy)为[Energy],其中Logtime> @first和Logtime< @st)

设置@max =(从PLENE_EnergySum中选择max(Energy)为[Energy],其中Logtime> @first和Logtime< @st)

设置@ result = @ max- @min

插入weekreport(周,能量)值('First',@ result)

回答上表:

首先961.1