当前位置:编程学习 > C#/ASP.NET >>

sql查询多层嵌套如何简化??


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.row_number()不需要
2.top 13、top 30也没必要分两步 --------------------编程问答--------------------
引用 1 楼 iceMung 的回复:
1.row_number()不需要
2.top 13、top 30也没必要分两步


是获取top30里的top13,不分两步怎么搞,并且每个子查询都有排序, --------------------编程问答-------------------- 第二层中直接就可以sum了吧,不用第三层了 --------------------编程问答--------------------
引用 2 楼 youaway 的回复:
...
是获取top30里的top13,不分两步怎么搞,并且每个子查询都有排序,


top 13是根据id来排序,而id又是根据year来排序的,说到底你就是一个表在那排来排去,ID根本没什么意义。
--------------------编程问答--------------------
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
--------------------编程问答-------------------- 可以用临时表,很好用的  临时表的使用  http://blog.sina.com.cn/s/blog_b5b6055e01014828.html
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,