|
/* 功能:sql server 2012应用之,如何查找连续性数据 作者:felix 日期:20200521 */ /* 所谓的连续性是指1,3,4,5,6,7,8,9,10这样的等差数列,或者1-1,1-2,1-3这样的连续日期 算法的基本原理是构造一个连续的序列,与需要被查找的序列进修比较,如果差相同则一定是连续的 */ --1,构建被查找序列 WITH cte_a (i) AS (SELECT 1 AS datalist UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 12 UNION ALL SELECT 15 UNION ALL SELECT 16 UNION ALL SELECT 189 UNION ALL SELECT 190 UNION ALL SELECT 191 UNION ALL SELECT 192), cte_b (i, l) --生成连续序列 AS (SELECT i, ROW_NUMBER() OVER (ORDER BY i) FROM cte_a), cte_c AS (SELECT cte_b.i, cte_b.l, i - l AS s FROM cte_b) SELECT * FROM cte_c AS a WHERE EXISTS ( SELECT * FROM ( SELECT s, COUNT(*) AS icount FROM cte_c GROUP BY cte_c.s HAVING COUNT(*) >= 4 --包含连续4个及以上元素的组 ) AS t WHERE a.s = t.s );

具有连续元素的组与构造连续序列的差是相同的 |
|