水表换表的sql语句(100分)

  • 主题发起人 主题发起人 huangjiahan
  • 开始时间 开始时间
H

huangjiahan

Unregistered / Unconfirmed
GUEST, unregistred user!
A表(水表换表记录):
id date1(换表时间) num1(换表前的数值) num2(换表后的值)
001 20021101 20 0
001 20021001 100 10
B表(水表报表):
id date1 date2 data1 data2
001 20020901 20021201 10 10
002 20020901 20021201 5 40
如上表,001号水表经历了2次换表,则001号水表在date1和date2之间的真正的的读数为
10-0+20-10+100-10=110.
这样的sql语句怎么写啊?
 
select b.id,sum(a.num1)-sum(a.num1)+sum(b.data1)-sum(data2) from a,b
where a.date1<b.date2 and a.date1>b.date1 and a.id=b.id
group by b.id
这样试试,不知有没有理解你的意思
 
问题的难点在于:报表的时间是不确定的,也就是说报表的这段时间刚好经历了2次换表,
则需计算2次,如果只经历了1次换表,则只能计算1次。
id date1 date2 data1 data2
001 20021025 20021201 5 40
则只经历了1次换表,
所有换表的次数是不定的。怎么办?
 
select data2-data1+
(select sum(num1-num2) from a where id=b.id and date1>b.date1 and date1<b.date2)
from b where id='001'
 
水表不只一个001啊
 
group by
分组
看不懂你的意思
 
jsxjd的語句意思比較明確,我的意見和他一致
不過我覺得這樣寫好一點,我沒試過,只是憑感覺寫的,你可以自己都去試試
select b.data2-b.data1+sum(a.num1-a.num2) from a,b where a.id=b.id and a.date1 between b.date1 and b.date2
and a.id='001'
 
update b set 用水量=data2-data1+
(select sum(num1-num2) from a where id=b.id and date1>b.date1 and date1<b.date2)
 

Similar threads

后退
顶部