您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關SQL開發實例和優化是怎樣的,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
找出連續的數據 如1,2,3,48,50,51,52,53,67,68
找出連續的數字的起點和重點
1,3
48,48
51,53
67,68
create table test.range_problem(
a int not null,
primary key (a));
insert into test.range_problem values(1);
insert into test.range_problem values(2);
insert into test.range_problem values(3);
insert into test.range_problem values(48);
insert into test.range_problem values(50);
insert into test.range_problem values(51);
insert into test.range_problem values(52);
insert into test.range_problem values(53);
insert into test.range_problem values(66);
insert into test.range_problem values(67);
--思路1 找最后一個不連續的數
SELECT T1.A
FROM test.range_problem T1
WHERE NOT EXISTS
(
SELECT A
FROM test.range_problem T2
WHERE T2.A -1 = T1.A
)
--思路2 找所有行對應的結束值
SELECT ROW_NUMBER()OVER(ORDER BY TBASE.A) ID
,TBASE.A
,(SELECT Min(A)
FROM test.range_problem T1
WHERE NOT EXISTS
(
SELECT A
FROM test.range_problem T2
WHERE T2.A -1 = T1.A
)
AND T1.A >= TBASE.A --T1.A 是3,48,53,67 TBASE.A 是每行的值
) A_END
FROM test.range_problem TBASE
--思路3 分組后找出所有連續的起始值和結束值
SELECT MIN(A) A_START, A_END
FROM(
SELECT ROW_NUMBER()OVER(ORDER BY TBASE.A) ID
,TBASE.A
,(SELECT Min(A)
FROM test.range_problem T1
WHERE NOT EXISTS
(
SELECT A
FROM test.range_problem T2
WHERE T2.A -1 = T1.A
)
AND T1.A >= TBASE.A --T1.A 是3,48,53,67 TBASE.A 是每行的值
) A_END
FROM test.range_problem TBASE
) T
GROUP BY T.A_END
--對上面語句的優化
WITH POT AS(
SELECT A
FROM test.range_problem T
WHERE NOT EXISTS
( SELECT A
FROM test.range_problem TC
WHERE TC.A -1 = T.A)
)
SELECT TBASE.A A_START,(SELECT MIN(A)
FROM POT T
WHERE TBASE.A <= T.A
) A_END
FROM test.range_problem TBASE
關于SQL開發實例和優化是怎樣的就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。