select sum(volume) from
(select top 13 * from 
(select top 30 * from 
(select row_number() over(order by year,cast(pindex as int) asc) as ID,*
 from v_offtakeptotal where family='EXTRA'
) t --一层
)tt --二层
order by id desc
)ttt--三层这个语句无非就是要获得EXTRA产品在某一年(year)某一期(PIndex,一年一共13期)之前的13期销量之和(包括该期)。备注:top  30 是根据计算得出要计算期(上文中的某一期)在order排序之后所在行数Rowid。这个语句虽可以达到效果,但是看起来比较别扭,请问这个语句能不能不嵌套这么多?有没有别的写法?本人sql较差,求指教。

解决方案 »

  1.   

    1.row_number()不需要
    2.top 13、top 30也没必要分两步
      

  2.   


    是获取top30里的top13,不分两步怎么搞,并且每个子查询都有排序,
      

  3.   

    第二层中直接就可以sum了吧,不用第三层了
      

  4.   


    top 13是根据id来排序,而id又是根据year来排序的,说到底你就是一个表在那排来排去,ID根本没什么意义。
      

  5.   

    SELECT sum(volume) FROM
    (select row_number() over(order by year,cast(pindex as int) asc) as ID,*
     from v_offtakeptotal where family='EXTRA'       
            ) t --一层
    WHERE ID BETWEEN 18 AND 30
      

  6.   

    可以用临时表,很好用的  临时表的使用  http://blog.sina.com.cn/s/blog_b5b6055e01014828.html