一个表,结构如下name         da            zh
a          2009-9-8        11
a          2009-9-7        2
a          2009-9-6        5
a          2009-9-4        3
a          2009-9-2        2
b          2009-9-8        11
b          2009-9-7        2
b          2009-9-6        5
b          2009-9-4        3
b          2009-9-2        2
c          ……
c          ……
……
name字段不止a、b、c三种值,还有很多值,da字段为date类型,也有很多不同的值,zh字段也有很多不同值。其中a的da值并不时连续的,如a的2009-9-5日期就不存在。现在想求出,group by name,da字段从大到小每3天zh字段的平均值,结果如下
name         date                   zh
a          2009-9-8-2009-9-6        6
a          2009-9-7-2009-9-4        5
a          2009-9-6-2009-9-2        5
b          2009-9-8-2009-9-6        6
b          2009-9-7-2009-9-4        5
b          2009-9-6-2009-9-2        5
c          ……
c          ……
……
请问sql 2000 语句如何写,恭谢!

解决方案 »

  1.   


    --测试数据
    declare @table table (name nvarchar(20),date char(10),zh int)
    insert into @table
    select 'a','2009-09-08',11 union all
    select 'a', '2009-09-07',2  union all
    select 'a','2009-09-06',5 union all
    select 'a', '2009-09-04',3  union all
    select 'a', '2009-09-02',2  union all
    select 'b','2009-09-08',11 union all
    select 'b', '2009-09-07',2  union all
    select 'b','2009-09-04',5 union all
    select 'b', '2009-09-06',3  union all
    select 'b', '2009-09-02',2  
    --查询
    select identity(int,1,1) as id,name,date,zh into #temp from @table order by name, date desc 
    select name,date+'-'+(select date from #temp where name = t.name and id = t.id + 2) as date,
    (select avg(zh) from #temp where name = t.name and id >= t.id and id <= t.id + 2 ) as zh
    from #temp t
    where date+'-'+(select date from #temp where name = t.name and id = t.id + 2) is not null
    --结果
    -----------------------------------------
    a 2009-09-08-2009-09-06 6
    a 2009-09-07-2009-09-04 3
    a 2009-09-06-2009-09-02 3
    b 2009-09-08-2009-09-06 5
    b 2009-09-07-2009-09-04 3
    b 2009-09-06-2009-09-02 3