表字段有:站号、日期、气温 
主键为站点和日期 现在查询2008年8月1号到3号气温总和、2009年8月1号到3号气温总和、以及两个的差值。 
我是这么写的: 
select s2.站号,sum(s1.气温), sum(s2.气温),sum(s2.气温)-sum(s1.气温) from 气象表 s1,气象表 s2 
where  s1.站号=s2.站号 
and s2.日期>=to_date('2009-8-1','yyyy-mm-dd') and s2.日期 <=to_date('2009-8-3','yyyy-mm-dd') 
and s1.日期>=to_date('2008-8-1','yyyy-mm-dd') and s1.日期 <=to_date('2008-8-3','yyyy-mm-dd') 
group by s2.站号; 这样查出来的结果总是实际值的3倍,我想是因为我累计了3天。我想还是关联条件的问题,因为主键是站号和日期,而关联条件只有站号。 
但是我又不知道怎么写,麻烦各位帮着看看。谢谢。

解决方案 »

  1.   

    select A.站号,A.气温 气温A,B.气温 气温B,A.气温-B.气温 气温差
    from 
    (select 站号,sum(气温) 气温 from s1 where to_char(日期,'YYYY-MM-DD') between '2008-08-01' and '2008-08-03' group by 站号)A,
    (select 站号,sum(气温) 气温 from s2 where to_char(日期,'YYYY-MM-DD') between '2008-09-01' and '2009-08-03' group by 站号)B,
    where A.站号=B.站号
      

  2.   

    子查询B年份错了,纠正:select A.站号,A.气温 气温A,B.气温 气温B,A.气温-B.气温 气温差 
    from 
    (select 站号,sum(气温) 气温 from s1 where to_char(日期,'YYYY-MM-DD') between '2008-08-01' and '2008-08-03' group by 站号)A, 
    (select 站号,sum(气温) 气温 from s2 where to_char(日期,'YYYY-MM-DD') between '2009-08-01' and '2009-08-03' group by 站号)B, 
    where A.站号=B.站号 
      

  3.   

    楼上的高手,不好意思,没太明白,“S1”是表吗?那么“A”是什么?还有“气温A” 是啥意思?
      

  4.   

    我套用运行了一下,最后一句“where A.站号=B.站号”提示说“表名无效”
    请问“A”和“B”能这样直接写吗?
      

  5.   


    可以select A.站号,A.气温 气温A,B.气温 气温B,A.气温-B.气温 气温差 
    from 
    (select 站号,sum(气温) 气温 from 气象表 s1 where to_char(日期,'YYYY-MM-DD') between '2008-08-01' and '2008-08-03' group by 站号)A, 
    (select 站号,sum(气温) 气温 from 气象表 s2 where to_char(日期,'YYYY-MM-DD') between '2009-08-01' and '2009-08-03' group by 站号)B
    where A.站号=B.站号 去掉了 B 后面的","
      

  6.   

    s1就是你原来的表,A,B都是别名 ,气温A也是
    select A.站号,A.气温 气温A,B.气温 气温B,A.气温-B.气温 气温差 
    from 
    (select 站号,sum(气温) 气温 from 气象表 s1 where to_char(日期,'YYYY-MM-DD') between '2008-08-01' and '2008-08-03' group by 站号) A, 
    (select 站号,sum(气温) 气温 from 气象表 s2 where to_char(日期,'YYYY-MM-DD') between '2009-08-01' and '2009-08-03' group by 站号) B
    where A.站号=B.站号 A和前面的(select ...)添个空格(B也一样):(select ...) A, (select....) B where.....
      

  7.   

    我就是这么套用的呀,源码是这么写的:select A.IIIII,A.V12004 气温A,B.V12004 气温B,A.V12004-B.V12004 气温差 
    from 
    (select IIIII,sum(V12004) 气温 from T_mete_history  where to_char(vdate,'YYYY-MM-DD') between '2008-08-01' and '2008-08-03' group by IIIII)A, 
    (select IIIII,sum(V12004) 气温 from T_mete_history  where to_char(vdate,'YYYY-MM-DD') between '2009-08-01' and '2009-08-03' group by IIIII)B
    where A.IIIII=B.IIIII;
    但是说第一行有错,无效的标识符,请问怎么回事呀?