如何查出这个值
我有一张表 id shuzi
1 93.5
2 82.5
3 76.5
4 65
5 54
6 63.5
7 70.5
8 53.5
9 58.5
10 68.5
如何能查找相邻3个id号所对应的sum值最大呢
(1,2,3)(2,3,4)(3,4,5)。。。
------解决方案--------------------
SELECT MAX(a) FROM (
SELECT SUM(a) a FROM person WHERE ID<4
UNION SELECT SUM(a) a FROM person WHERE ID<5 AND ID>1
UNION SELECT SUM(a) a FROM person WHERE ID<6 AND ID>2
UNION SELECT SUM(a) a FROM person WHERE ID<7 AND ID>3
……………………………………………………………………………………
UNION SELECT SUM(a) a FROM person WHERE ID<11 AND ID>7
)
随手写的,这个方法比较笨,单纯的SQL是不可能实现的吧,但用PL-SQL很容易实现只要把上面id的范围写成动态的就可以。
------解决方案--------------------WITH TEST AS (
SELECT '01' AS ID,93.5 AS SHUZI FROM DUAL
UNION ALL
SELECT '02' AS ID,82.5 AS SHUZI FROM DUAL
UNION ALL
SELECT '03' AS ID,76.5 AS SHUZI FROM DUAL
UNION ALL
SELECT '04' AS ID,65 AS SHUZI FROM DUAL
UNION ALL
SELECT '05' AS ID,54 AS SHUZI FROM DUAL
UNION ALL
SELECT '06' AS ID,63.5 AS SHUZI FROM DUAL
UNION ALL
SELECT '07' AS ID,70.5 AS SHUZI FROM DUAL
UNION ALL
SELECT '08' AS ID,53.5 AS SHUZI FROM DUAL
UNION ALL
SELECT '09' AS ID,58.5 AS SHUZI FROM DUAL
UNION ALL
SELECT '10' AS ID,68.5 AS SHUZI FROM DUAL
)
SELECT GREATEST(SHUZI, NS, NNS) AS RESULTSHUZI
FROM (SELECT SHUZI,
LEAD(SHUZI, 1) OVER(ORDER BY ID) AS NS,
LEAD(SHUZI, 2) OVER(ORDER BY ID) AS NNS
FROM TEST)
WHERE GREATEST(SHUZI, NS, NNS) IS NOT NULL
================================================================
1 93.5
2 82.5
3 76.5
4 65
5 70.5
6 70.5
7 70.5
8 68.5
------解决方案--------------------
WITH tb AS (
SELECT 1 id,93.5 shuzi FROM DUAL UNION AL