使用CTE循环的每日快照表

时间:2018-11-08 15:44:12

标签: sql common-table-expression sql-server-2016

我需要每天快照一下在给定的一天(定义为Start_Date和End_Date之间的@date)中有多少员工,每个日期一行。

有一点,下面的脚本将返回所有每日快照,但是它们分别在单独的结果窗口中返回。我无法获得将所有结果合并以将每个新结果插入#PLEASEWORK的查询。

我需要使以下内容连续两天工作。它使用int个日期。我已经继承了这个问题,并正在建立一个日期表来解决该问题。

CREATE TABLE #PLEASEWORK
(
    [Date] INT
    ,Division_Description VARCHAR (100)
    ,[Count] INT
)

DECLARE @cnt AS INT
DECLARE @DATE AS INT

SET @CNT = '20181001'

WHILE @cnt >= @DATE

BEGIN

SELECT @DATE = '20181031' - 1


TRUNCATE TABLE #PLEASEWORK
INSERT INTO #PLEASEWORK

SELECT
    @DATE [date]
    ,Division_Description
    ,COUNT(*) [Count]
--INTO #PLEASEWORK
FROM EmpMaster

WHERE
    ([Start_Date] <= @DATE
    AND Leaving_Date = 0)
    OR ([Start_Date] <= @DATE
    AND Leaving_Date > @DATE)

GROUP BY
    Division_Description


SET @cnt = @cnt + 1

CONTINUE


SELECT *

FROM #PLEASEWORK

END

1 个答案:

答案 0 :(得分:1)

您可以在一个查询中完成所有这些操作。这是一种方法(不是最有效的),但应该可以使用一个月。

Level = {
  id: "some_id",
  name: "some_name",
  Settings: [
    Type: "sometype",
    Difficulty: {
      id: "difficulty_id"
    }
  ]
}

使用declare @DATESTART date = '20181001'; declare @DATEEND date = '20181031'; with dates as ( select @DATESTART as dte union all select dateadd(day, 1, dte) from dates where dte < @DATEEND ) select d.dte, dd.Division_Description, (select count(*) from EmpMaster e where e.Division_Description = dd.Division_Description and e.start_date <= d.dte and (e.leaving_date >= d.dte or e.leaving_date is null) ) as num_employees from dates d cross join (select distinct Division_Description from EmpMaster) dd order by d.dte, dd.Division_Description; 上的索引,这应该比基于游标的方法好得多。