相忘于江湖

不抛弃,不放弃... 请给我勇敢,改变可以改变的;请给我坚强,接受不可以改变的;请给我智慧,分辨这两者。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

有一个表a1,表中记录是:
user_no acct_month charge
0001 200505 1.00
0001 200506 2.00
0001 200507 3.00
0002 200505 4.00
0002 200506 5.00
0002 200507 6.00
我想显示成这种格式,sql如何写?
user_no 5月金额 6月金额 7月金额
0001       1.00        2.00        3.00
0002       4.00        5.00        6.00

 

select user_no,
sum(decode(acct_month,'200505',charge,0) 5月金额,
sum(decode(acct_month,'200506',charge,0) 6月金额,
sum(decode(acct_month,'200507',charge,0) 7月金额
from a1 group by user_no

 

 

select b1.user_no,
sum(b1.5_charge) AS 5月金额,
sum(b1.6_charge) AS 6月金额,
sum(b1.7_charge) AS 7月金额
from
(select user_no,
(case when acct_month= '200505' then
charge
end ) AS 5_charge,
(case when acct_month= '200506' then
charge
end ) AS 6_charge,
(case when acct_month= '200507' then
charge
end ) AS 7_charge
from a1) b1
group by b1.user_no

 

select user_no,
sum(case acct_month when '200505' then charge else 0 end ) 5月金额,
sum(case acct_month when '200506' then charge else 0 end ) 6月金额,
sum(case acct_month when '200507' then charge else 0 end ) 7月金额
from a1 group by user_no
其实case和decode差不多的,但是case是oracle9i中新增的特性,如果在9i以下的数据库使用是要报错的。

posted on 2010-07-17 15:19  playman0211  阅读(328)  评论(0编辑  收藏  举报