数字辅助表:连续范围的结果处理


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
数字辅助表:一个1到N的表 应用:连续范围的结果处理,利用group by会有缺失范围!

创建此函数,每次调用 select dbo.fn_nums(24)即可:
CREATE FUNCTION dbo.fn_nums(@n AS BIGINT) RETURNS TABLE
AS
RETURN
  WITH
  L0   AS(SELECT 1 AS c UNION ALL SELECT 1),
  L1   AS(SELECT 1 AS c FROM L0 AS A, L0 AS B),
  L2   AS(SELECT 1 AS c FROM L1 AS A, L1 AS B),
  L3   AS(SELECT 1 AS c FROM L2 AS A, L2 AS B),
  L4   AS(SELECT 1 AS c FROM L3 AS A, L3 AS B),
  L5   AS(SELECT 1 AS c FROM L4 AS A, L4 AS B),
  Nums AS(SELECT ROW_NUMBER() OVER(ORDER BY c) AS n FROM L5)
  SELECT n FROM Nums WHERE n <= @n;
--注对于n级,最大的行数为2的(2的n次幂)次幂 如n=5时,最大行数为:2的32次方共4294967296行数据!
GO

应用:1,一段日期范围内的订单数,可以用group by,但得不到连续的日期,即若某天没有业绩,就显示不出来,所以用group by有缺陷
数字辅助表:
DECLARE @OrderDateBegin VARCHAR(20),@OrderDateEnd VARCHAR(20)
SET @OrderDateBegin = '2011-01-01'
SET @OrderDateEnd = '2011-02-01'
DECLARE @Span INT
SET @Span = DATEDIFF(dd,@OrderDateBegin,@OrderDateEnd)
--SELECT @Span

SELECT DATEADD(dd,fn.n-1,@OrderDateBegin),
(SELECT COUNT(1) FROM bdorder b(NOLOCK)
 WHERE b.OrderDate>=DATEADD(dd,fn.n-1,@OrderDateBegin)
       AND b.OrderDate < DATEADD(dd,fn.n,@OrderDateBegin) )
FROM dbo.fn_nums(@Span) fn

2,与上面类似,但查询一天每个时间段的数据时或每几个时间段的数据时,也可通过上面的方法处理!