还是昨天问的有关视图的问题。。(50分)

I

imacih

Unregistered / Unconfirmed
GUEST, unregistred user!
Table:
ID Amount MaxAmount Month
1 100 999 1
2 400 999 1
3 900 999 1
4 89 99 1
1 300 999 2
2 700 999 2
3 200 999 2
4 50 99 2
1 500 999 3
2 80 999 3
3 700 999 3
4 99 99 3
1。。。。
2。。。。
。。。
这是有关电表的表,其中ID标识不同的电表,Amount为电表上的读数,MaxAmount为电表能显示的最大值,Month为月份(这里只有3个月,但实际情况有几个月是不知道的)。
现在要创建一个月电表用电量的视图,其中用电量为
用电量 = 本月度数 - 上月度数, 如果本月度数比上月度数小的话,说明电表已经转过了能显示的最大值,并且从0再开始计数(虽然本月度数比上月度数大时亦有此可能,但这里不考虑),
此时
用电量 = 本月度数 - 上月度数 + 能显示的最大值 + 1。
因此按上表,得出的视图如下:
ID UsedAmount Month
1 200 2
2 300 2
3 300 2
4 61 2
1 200 3
2 380 3
3 500 3
4 49 3
1。。。
2。。。
。。。

本人想实现该视图时遇到两大难点:
(1)本月度数比上月度数小时与一般情况下的计算用电量方法不同(不知道SQL中怎样分情况考虑);
(2)如果表有N个月份的数据,则视图要有N-1个月份的用电量,所以不知道怎样用Where语句。

在这里望大侠能给小弟指点一下,谢谢!
 
SELECT distinct id,month,
(select amount from table1 where id=AAA.id and month=AAA.month-1) as 上月,
(select amount from table1 where id=AAA.id and month=AAA.month ) as 本月,
iif(本月-上月<0,本月-上月+maxamount+1,本月-上月) as usedamount
from table1 AAA
where month>1
order by month,id

在access里的写法
 
SELECT ID,MONTH,本月-上月 usedamount
FROM
(SELECT distinct id,month,maxamount,
(select amount from table1 where id=AAA.id and month=AAA.month-1) 上月,
(select amount from table1 where id=AAA.id and month=AAA.month ) 本月
from table1 AAA where month>1) BBB
WHERE 本月-上月>=0
UNION
SELECT ID,MONTH,本月-上月+MAXAMOUNT+1 usedamount
FROM
(SELECT distinct id,month,maxamount,
(select amount from table1 where id=AAA.id and month=AAA.month-1) 上月,
(select amount from table1 where id=AAA.id and month=AAA.month ) 本月
from table1 AAA where month>1) BBB
WHERE 本月-上月<0
ORDER BY MONTH,ID

MSSQL里的写法,不过我觉得这句还不是很好
 
SELECT ID,MONTH,( CASE WHEN 本月-上月>0 THEN 本月-上月 ELSE 本月-上月+MAXAMOUNT+1 END) USEDAMOUNT
FROM
(SELECT distinct id,month,maxamount,
(select amount from table1 where id=AAA.id and month=AAA.month-1) 上月,
(select amount from table1 where id=AAA.id and month=AAA.month ) 本月
from table1 AAA where month>1) BBB
ORDER BY MONTH,ID
 
电费管理?
我刚好也在做,能不能给参考参考,交流交流,谢谢。
glbboy@163.com
 

Similar threads

S
回复
0
查看
1K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
958
SUNSTONE的Delphi笔记
S
D
回复
0
查看
562
DelphiTeacher的专栏
D
S
回复
0
查看
987
SUNSTONE的Delphi笔记
S
S
回复
0
查看
805
SUNSTONE的Delphi笔记
S
顶部