asw_id代表一个点位,recordtime 代表记录时间, rec_date 代表记录日期,DAYRF 代表当前点位累计积水量的数值。
求每个点位在一个时间区间内的累计积水量
难点:
DAYRF 代表当前点位累计积水量的数值,是指当天从8点到当前时间的累计积水量。
recordtime 数值格式12:00即 1200 8点5分即 805
rec_date 数值格式 2014-09-24 即140924
特殊数值 每天早晨8点的数据,代表前一天早晨8点到今天8点的累计积水量,
8点后 积水量从0开始计算 从新累计
create table
(
id CHAR(22) not null,
aws_id CHAR(10),
recordtime NUMBER(4),
rec_date NUMBER(8),
dayrf NUMBER(5,1),
)
参考数据
1,‘10001’,‘140924’,800,100
2,‘10001’,‘140924’,900,0
3,‘10001’,‘140924’,1000,0
4,‘10001’,‘140924’,1100,100
5,‘10001’,‘140924’,2300,100
6,‘10001’,‘140925’,600,100
7,‘10001’,‘140925’,800,100
8,‘10001’,‘140925’,900,0
9,‘10001’,‘140925’,1200,100
10,‘10001’,‘140925’,2000,200
11,‘10001’,‘140926’,800,200
验证
查询9月24日8点到25日8点 返回结果为‘10001’,100
查询9月24日8点到25日12点 返回结果为‘10001’,200
查询9月24日8点到25日20点 返回结果为‘10001’,300
查询9月24日8点到26日8点 返回结果为‘10001’,400
------解决思路----------------------
终于搞出来了。感觉着表结构设计的让人心碎啊
with cte as
(select rec_date, case when convert(int,recordtime)<800
then rec_date-1 else rec_date end as rec_date1,recordtime,dayrf from test),
cte1 as
(select rec_date,dayrf from test where recordtime='800'),
cte2 as
(select A.REC_DATE,SUM(convert(int,B.DAYRF)) AS DAYSUM from cte1 as a join cte1 as b on a.rec_date>=b.rec_DATE
group by a.rec_date),
cte3 as
(select rec_date,rec_date1,recordtime,case when recordtime='800' then '0' else dayrf end as dayrf from cte )
select rec_date1,recordtime,dayrf+DAYSUM as daysum from cte3 join cte2 on cte2.rec_date=cte3.rec_date1
--结果,你要求任何2个时间点的间隔只要把这2个时间点的数值相减就好了。
rec_date1 recordtime daysum
----------- ---------- -----------
140924 800 100
140924 900 100
140924 1000 100
140924 1100 200
140924 2300 200
140924 600 200
140925 800 200
140925 900 200
140925 1200 300
140925 2000 400
140926 800 400