用一条查询语句取出price的和最大的连续5条记录

事情起因是由csdn上的一个问题引起的.(详见http://topic.csdn.net/u/20071006/18/b5c31f64-ff1f-4f55-9caf-f3c680a469c7.html?seed=305126211)

题目3:有一个表 ordertable(price money,id int), 表中有50条记录,其中price中数据是不规则的,要求用一条查询语句取出price的和最大的连续5条记录
 例如:
1 10.00
2 5.00
3 6.00
4 8.00
5 1.00
6 20.00
7 60.00
8 4.00
9 3.00
10 2.00
11 80.00
12 120.00
13 1.00

和最大的连续5条记录就是
8 4.00
9 3.00
10 2.00
11 80.00
12 120.00

我见好多人都没把楼上的题意审清楚就搞了N多的解决方法 ,当然此题目对我而言也是有难度的,后来我找的我一位朋友帮我求出.一时没有理解透彻,记一下,以后慢慢理解.

请大家看清楚题目---要求用一条查询语句取出price的和最大的连续5条记录

这个题目应该说是要对sql语句理解到一个层次上才可以.不仅仅是简单的select如斯简单的了.部分答案如下...

SELECT DISTINCT t1.id, t2.id, t3.id, t4.id, t5.id, t1.price+t2.price +t3.price+t4.price +t5.price
FROM [select t1.*,t2.*,t3.*,t4.*,t5.* from ordertable t1,ordertable t2,ordertable t3,ordertable t4 ,ordertable t5,ordertable t6
where t1.id<t2.id and t2.id<t3.id and t3.id<t4.id and t4.id<t5.id
and not exists (select id from ordertable  a where (a.id>t1.id and a.id<t2.id ) or (a.id>t2.id and a.id<t3.id)
or(a.id>t3.id and a.id<t4.id) or(a.id>t4.id and a.id<t5.id)
)]. AS p;


下载附件

原文地址:https://www.cnblogs.com/sxlfybb/p/916825.html