求语句:计算水量同比和水费同比

blue_apple 2009-03-13 05:17:40


表t 里的数据
月份 水价 本月水量 本月水费
200801 1.00 5000 5000
200801 2.00 1000 2000
200802 1.00 5500 5500
200802 2.00 1800 3600
。。。
200901 1.00 6000 6000
200901 2.00 8000 16000
200901 2.50 1000 2500

以水价分类,求2009年1月水量和水费与2008年1月的水量和水费的比

水价 水量同比 水费同比
1.00 1.2 1.2
2.00 8 8
2.5 0 0
...全文
104 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
dawugui 2009-03-13
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 blue_apple 的回复:]
up
[/Quote]
1楼已经帮你算出来了,还UP?
blue_apple 2009-03-13
  • 打赏
  • 举报
回复
up
htl258_Tony 2009-03-13
  • 打赏
  • 举报
回复
declare @t table (月份 varchar(10), 水价 dec(5,2),本月水量 int,本月水费 int)
insert @t select '200801', 1.00 , 5000 , 5000
insert @t select '200801', 2.00 , 1000 , 2000
insert @t select '200802', 1.00 , 5500 , 5500
insert @t select '200802', 2.00 , 1800 , 3600
insert @t select '200901', 1.00 , 6000 , 6000
insert @t select '200901', 2.00 , 8000 , 16000
insert @t select '200901', 2.50 , 1000 , 2500

select
水价=isnull(a.水价,b.水价),
水量同比=case when a.水价 is null or b.水价 is null then 0 else cast(cast(b.本月水量 as dec(10,2))/cast(a.本月水量 as dec(10,2)) as dec(3,1)) end,
水费同比=case when a.水价 is null or b.水价 is null then 0 else cast(cast(b.本月水费 as dec(10,2))/cast(a.本月水费 as dec(10,2)) as dec(3,1)) end
from
(select * from @t where 月份='200801') a
full join
(select * from @t where 月份='200901') b
on a.月份=cast(left(b.月份,4)-1 as varchar)+right(b.月份,2)
and a.水价=b.水价

水价 水量同比 水费同比
------- ----- -----
1.00 1.2 1.2
2.00 8.0 8.0
2.50 0 0

(所影响的行数为 3 行)

22,210

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧