table1 
 日期       数据
2007-9-30   100
2007-6-30   200
2006-9-30   50
2006-6-30   50求的不同年份,相同月日的数据增长率((今年-去年)/去年)*100  日期       数据  增长率
2007-9-30   100  100%
2007-6-30   200  300%
2006-9-30   50   NULL
2006-6-30   50   NULL我写的sql语句 
select 日期,数据,(((数据-去年)/去年)*100) as 增长率 from 
(
  select 日期,数据,(select 数据 from table1 t2 where t2.日期=t1.DATEADD(year, -1, t1.日期)) as 去年 
  from table1 t1
)
可是发现数据量大的时候效率太差了,请问有其他办法吗?

解决方案 »

  1.   

    declare @tb table (日期 datetime,数据 int)
    insert into @tb select '2007-9-30',100
    insert into @tb select '2007-6-30',200
    insert into @tb select '2006-9-30',50
    insert into @tb select '2006-6-30',50select a.日期,a.数据,ltrim(cast((a.数据-b.数据)*100.0/b.数据 as decimal(10,0)))+'%'  as '增长率'
    from @tb a left join (select dateadd(yy,1,日期) as 日期,数据 from @tb where datename(yy,日期)='2006')b
    on a.日期=b.日期 
    日期                    数据    增长率
    2007-09-30 00:00:00.000 100 100%
    2007-06-30 00:00:00.000 200 300%
    2006-09-30 00:00:00.000 50 NULL
    2006-06-30 00:00:00.000 50 NULL会好点不?
      

  2.   

    create table tb(日期 datetime,数据 int)
    insert into tb select '2007-9-30',100
    insert into tb select '2007-6-30',200
    insert into tb select '2006-9-30',50
    insert into tb select '2006-6-30',50
    goselect a.* , [增长率(%)] = ((a.数据 - b.数据)/b.数据)*100 from tb a left join tb b on a.日期 = dateadd(yy , 1 , b.日期)drop table tb/*
    日期                                                     数据          增长率(%)      
    ------------------------------------------------------ ----------- ----------- 
    2007-09-30 00:00:00.000                                100         100
    2007-06-30 00:00:00.000                                200         300
    2006-09-30 00:00:00.000                                50          NULL
    2006-06-30 00:00:00.000                                50          NULL(所影响的行数为 4 行)
    */