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

跪求高手赐教 sql查询问题
数据库有两张表:
A表(工程下载收入表):projectid ,downloadIncome ,time(yyyy-MM-dd)
B表(工程广告收入表):projectid , adIncome ,time(yyyy-MM-dd)

这两个表没有直接联系,现在需要将同一个工程的下载收入(downloadIncome )和广告收入(adIncome )以及时间查出来,一天一个工程只会分别在这两张表中最多只一次。问题是某一天可能此工程只有下载收入记录或者是只有广告收入记录

比如:A表数据如:
1 , 100 , ‘2010-04-10’
1 , 200 , ‘2010-04-11’

  B表数据如:
1 , 100 , ‘2010-04-10’
1 , 300 , ‘2010-04-12’
-----------------------------
需要查询之后出现的效果是:  
 downloadIncome ,adIncome , time
 100 100 ‘2010-04-10’
 200 null(或0)‘2010-04-11’
null(或0) 300 ‘2010-04-12’

跪等~!


------解决方案--------------------
SQL code
select projectid,sum(downloadIncome),sum(adIncome),time 
from (
select projectid,downloadIncome ,0 as adIncome , time from A表
union all
select projectid ,0, adIncome ,time from B表
) t
group by projectid,time
order by time

------解决方案--------------------
SQL code
--还是写一个吧,2楼少关联了一个条件 
with a as(
select 1 projectid, 100 downloadincome, date'2010-04-10' time from dual union all                       
select 1 projectid, 200 downloadincome, date'2010-04-11' time from dual),
b as(
select 1 projectid, 100 adincome, date'2010-04-10' time from dual union all                       
select 1 projectid, 300 adincome, date'2010-04-12' time from dual)

SELECT nvl(a.projectid, b.projectid) projectid,
  nvl(a.downloadincome, 0) downloadincome,
  nvl(b.adincome, 0) adincome,
  nvl(a.time, b.time) TIME
FROM a
FULL OUTER JOIN b
  ON (a.projectid = b.projectid AND a.time = b.time);