连续范围查询

总则:观察规律,将规律固定下来。
连续范围:1,2,3,4,7,8,11,12,15
连续范围为:1,2,3,4 | 7,8 |11,12
特点:若按从小到大的顺序给行号,则在连续范围中的与行号相减,应为一固定数值
如:
字段值 行号 相减值
1 1 0
2 2 0
3 3 0
4 4 0
7 5 2
8 6 2
11 7 4
12 8 4
15 9 6
相减值相对的是处于连续范围内,按此值分组,求最小字段值、最大字段值即是连续范围

如: 求6月份连续业绩大于100万的日期范围
第一:求日期相减值; 第二:分组求范围

/*6月份业绩超过100万的日期范围*/
WITH DayAchievement AS(
SELECT CONVERT(VARCHAR(10),bo.OrderDate,120) OrderDate,SUM(amount) OrderSum
FROM bdOrder bo(NOLOCK)
JOIN mdOrderStatus mos(NOLOCK) ON bo.OrderStatus = mos.StatusCode AND mos.IsAchievement = 1
WHERE bo.OrderDate >=’2011-06-01′
GROUP BY CONVERT(VARCHAR(10),bo.OrderDate,120)
)

SELECT MIN(OrderDate),MAX(OrderDate),
DATEDIFF(dd,MIN(OrderDate),MAX(OrderDate))+1,
SUM(OrderSum)
FROM (
SELECT a.OrderDate,a.OrderSum,DATEADD(dd,-1 * ROW_NUMBER() OVER ( ORDER BY a.OrderDate)+1,a.OrderDate) gy
FROM DayAchievement a
WHERE OrderSum >= 1000000
)m
GROUP BY gy

注:DATEADD(dd,-1 * ROW_NUMBER() OVER ( ORDER BY a.OrderDate)+1,a.OrderDate) gy 即是相减值(规律值)