日期:2014-05-17  浏览次数:20700 次

请教下sql语句应该怎么写
现在有两张表,其中需要主要的字段有 表A : 房屋id  日期   金额  类别(里面有水费,点费,其它什么的)  然后表B: 房屋id  日期  金额  类别(里面也有水费,点费 ,但两个表里有可能其中的类别只有一个有)    现在需要的是取出 按照房屋 日期 类别 进行金额的统计 就是一个房间 这一天  各种类别费用的累加  。我应该怎么进行分组才能取出来啊? 因为两个类别里有相同的 也有不同的 谢谢了啊
sql

------解决方案--------------------
如果类别是固定的几种 不知道这么做可以么.


with t1 as
(
     select 1 rid,date'2013-09-10' rdate,2 tid,50 money from dual union all
     select 1 rid,date'2013-09-10' rdate,4 tid,40 money from dual union all
     select 2 rid,date'2013-09-11' rdate,1 tid,100 money from dual 
),t2 as
(
     select 1 rid,date'2013-09-10' rdate,1 tid,100 money from dual union all
     select 2 rid,date'2013-09-11' rdate,2 tid,150 money from dual union all
     select 1 rid,date'2013-09-11' rdate,3 tid,120 money from dual union all
     select 2 rid,date'2013-09-11' rdate,1 tid,110 money from dual  
)

select rid,rdate,
       sum(decode(tid,1,money,0)) "类别1",sum(decode(tid,2,money,0)) "类别2",
       sum(decode(tid,3,money,0)) "类别3",sum(decode(tid,4,money,0)) "类别4"
       
from (select * from t1 union all select * from t2) t
group by rid,rdate
order by rid,rdate


     rid     rdate   类别1  类别2  类别3  类别4
------------------------------
1 1 2013/9/10 100 50 0 40
2 1 2013/9/11 0 0 120 0
3 2 2013/9/11 210 150 0 0


------解决方案--------------------