sql 统计时间区间各区间出现的次数

CREATE TABLE #temp
    (
      FName NVARCHAR(10) ,
      FStartDate DATETIME ,
      FEndDate DATETIME
    );

INSERT  #temp
        ( FName, FStartDate, FEndDate )
VALUES  ( '1#', '2022-04-12 08:00:00', '2022-04-12 17:00:00' )
,       ( '2#', '2022-04-12 08:00:00', '2022-04-12 13:00:00' )
,       ( '3#', '2022-04-12 12:00:00', '2022-04-12 17:00:00' )
,       ( '4#', '2022-04-12 08:00:00', '2022-04-12 17:00:00' );



CREATE TABLE #tempdate
    (
      FName NVARCHAR(10) ,
      FStartDate DATETIME ,
      FEndDate DATETIME
    );

DECLARE @FName NVARCHAR(20) ,
    @FStartDate DATETIME ,
    @FEndDate DATETIME;

/* 声明游标,默认为FORWARD_ONLY游标 */
DECLARE cur CURSOR
FOR
    SELECT  *
    FROM    #temp;

 /* 打开游标 */
OPEN cur;

/* 读取第1行数据*/
FETCH NEXT FROM cur INTO @FName, @FStartDate, @FEndDate; 
WHILE @@FETCH_STATUS = 0 /* 用WHILE循环控制游标活动 */
    BEGIN
	 
        WITH    qj
                  AS ( SELECT   FDate ,
                                ROW_NUMBER() OVER ( ORDER BY t.FDate ) FIndex
                       FROM     ( SELECT    FStartDate FDate
                                  FROM      #temp
                                  WHERE     FStartDate >= @FStartDate
                                            AND FStartDate <= @FEndDate
                                  UNION ALL
                                  SELECT    FEndDate
                                  FROM      #temp
                                  WHERE     FEndDate >= @FStartDate
                                            AND FEndDate <= @FEndDate
                                ) t
                       GROUP BY FDate
                     )
            INSERT  #tempdate
                    ( FName ,
                      FStartDate ,
                      FEndDate
                    )
                    SELECT  @FName ,
                            a.FDate ,
                            b.FDate
                    FROM    qj a
                            LEFT JOIN qj b ON b.FIndex = a.FIndex + 1
                    WHERE   b.FDate IS NOT NULL;

	 /* 在循环体内将读取其余行数据 */
		FETCH NEXT FROM cur INTO @FName, @FStartDate, @FEndDate; 
    END;

/* 关闭游标 */
CLOSE cur; 

/* 删除游标 */
DEALLOCATE cur; 

SELECT * FROM #temp a
LEFT JOIN #tempdate b ON b.FName=a.FName
OUTER APPLY(SELECT COUNT(oa.FName) num FROM #temp oa WHERE oa.FName!=a.FName AND oa.FStartDate<=b.FStartDate AND oa.FEndDate >=b.FEndDate)o

DROP TABLE #temp; 
DROP TABLE  #tempdate

  

posted @ 2022-04-12 10:14  瓜甜  阅读(485)  评论(0编辑  收藏  举报