表字段有:站号、日期、气温 
主键为站点和日期 现在要得到本年某个时间段的气温总和,以及常年这个时间段的气温总和,最后计算二者的差,用来比较本年和常年此时间段累计气温。
比如用户选择了1971到2000年代表常年,现在要计算2009年1月1号到31号的气温总和;还要计算1971年到2000年每年的1月1号到31号的气温总和,然后将30个值进行平均,这就是常年值。
要显示的就是2009年的1月气温总和、常年值、二者的差值请问这个select语句该怎么写?比较复杂,我都晕了。

解决方案 »

  1.   

    1、表结构和测试数据,如下:
     站号       日期           气温
    SITES    DAYDATE      TEMPER    
      1 2001-1-1 5
      2 2001-1-1 4
      3 2001-1-1 6
      1 2001-1-2 3
      2 2001-1-2 5
      3 2001-1-2 7
      1 2002-1-1 5
      2 2002-1-1 4
      3 2002-1-1 6
      1 2002-1-2 5
      2 2002-1-2 2
      3 2002-1-2 5
      1 2003-1-1 4
      2 2003-1-1 5
      3 2003-1-1 1
      1 2003-1-2 6
      2 2003-1-2 2
      3 2003-1-2 32、Sql语句如下:
       2003年的1月气温总和、2001-2002常年值、二者的差值。   Select A1.站号, A1.气温总和, A2.常年值, A1.气温总和 - A2.常年值 As 二者的差值
       From (Select T1.Sites As 站号, Sum(T1.Temper) As 气温总和
     From Temperature T1
     Where To_Char(T1.Daydate, 'YYYYMM') = '200301'
     Group By T1.Sites) A1,
     (Select T2.Sites As 站号, Sum(T2.Temper) / 2 As 常年值
     From Temperature T2
     Where To_Char(T2.Daydate, 'YYYYMM') Between '200101' And '200201'
     Group By T2.Sites) A2
       Where A1.站号 = A2.站号;
       查询结果如下:
       站号  气温总和  常年值  二者的差值
        1  10  9  1
        2  7  7.5  -0.5
        3  4  12  -8
      

  2.   

    好像不对吧?我要计算1971到2000年 每年1月1号到10号的呢?而且时间段和日期都是可以变的,并不只有2001和2002年两年啊。
    并且“To_Char(T2.Daydate, 'YYYYMM') Between '200101' And '200201' ”
    这么写成了计算2001年1月到2002年1月的了,它们中间有13个月了,而我只要计算每年的特定时段。
      

  3.   

    select a.站号,(a.气温/a.num-b.气温/b.num) 气温差
    from
    (select 站号,sum(气温) 气温,count(*) num 
    from tb where 日期 between '2009-01-01' and '2009-01-02' group by 站号)a,
    (select 站号,sum(气温) 气温,count(*) num 
    from tb where 日期 between '1971-01-01' and '2000-01-02' group by 站号)b
    where a.站号=b.站号
      

  4.   

    楼上的大虾还是没明白我的意思,“日期 between '2009-01-01' and '2009-01-02' ”这个是对的
    但是常年值应该是1971年1月1号到1971年1月2号的气温之和、1972年1月1号到1972年1月2号的气温和、1973年1月1号到1973年1月2号的气温和......、1999年1月1号到1999年1月2号的气温和、2000年1月1号到2000年1月2号的气温和。
    而不是把1971到2000年所有日期的气温都一股脑加起来。
      

  5.   

    select a.站号,(a.气温/a.num-b.平均气温/b.年数) 气温差 
    from 
    (select 站号,sum(气温) 气温,count(*) num 
    from tb where 日期 between '2009-01-01' and '2009-01-02' group by 站号)a, 
    (select 站号,agv(气温/num) 平均气温,count(*) 年数
    from (select 站号,substr(to_char(日期,'YYYY-MM-DD'),1,4) 年份,sum(气温) 气温,count(*) num 
    from tb 
    where substr(to_char(日期,'YYYY-MM-DD'),1,4) between '1971' and '2000' 
    and substr(to_char(日期,'YYYY-MM-DD'),6,5) between '01-01' and '01-02' group by 站号
    group by 站号,substr(to_char(日期,'YYYY-MM-DD'),1,4)
    ) group by 站号
    )b 
    where a.站号=b.站号 
      

  6.   

    太好了!我已经调通了,谢谢大家!更谢谢楼上的hdhai9451 !