根据日期列表从数据获取统计信息

时间:2018-07-30 19:18:53

标签: sql sql-server

我有很多票。这些票证具有创建日期和完成日期。我正在尝试获取给定日期有多少张票的历史清单。即,对于日期顺序列表中的任意日期,在该日期之前(或当天)打开了几张票,并在该日期之后关闭(或关闭日期为空)。

dbo.wh_task中的相关列如下:

task_number         create_time                 date_completed   
T20180619.0041      2018-06-19 19:37:24.727     2018-06-26 23:36:21.613
T20180619.0048      2018-06-19 20:41:07.800     2018-06-27 19:26:43.480
...                 ...                         ...

我已经走了这么远:

DECLARE @Dates table (
  day DATE,
  PRIMARY KEY (day)
)
DECLARE @dIncr DATE = '2016-01-01'
DECLARE @dEnd DATE = CAST(GetDate() as DATE)

WHILE ( @dIncr < @dEnd )
BEGIN
  INSERT INTO @Dates (day) VALUES( @dIncr )
  SELECT @dIncr = DATEADD(DAY, 1, @dIncr )


-- --------------------------------
SELECT
  @Dates.day,
  COUNT(tickets.task_number) AS CountOfOpenTickets
FROM @Dates 
LEFT JOIN dbo.wh_task tickets ON Dates.day BETWEEN tickets.create_time AND tickets.date_completed

运行代码时,我得到SQL Error (102): Incorrect syntax near 'date_completed'. 我不太确定该从哪里去,因为该错误的描述性不是太强。

2 个答案:

答案 0 :(得分:1)

似乎查询中@dates表的别名使用不当,并且聚合函数group by缺少Count子句。您可以尝试此查询。另外,请确保您有END用于WHILE循环。

SELECT
  d.day,
  COUNT(tickets.task_number) AS CountOfOpenTickets
FROM @Dates as d
LEFT JOIN dbo.wh_task tickets ON d.day BETWEEN tickets.create_time AND tickets.date_completed
group by d.day

答案 1 :(得分:0)

如果任何人谷歌搜索想要查看工作代码。谢谢维尼特!

DECLARE @Dates table (
  day DATE,
  PRIMARY KEY (day)
)
DECLARE @dIncr DATE = '2016-01-01'
DECLARE @dEnd DATE = CAST(GetDate() as DATE)

WHILE ( @dIncr <= @dEnd)
BEGIN
  INSERT INTO @Dates (day) VALUES( @dIncr )
  SELECT @dIncr = DATEADD(DAY, 1, @dIncr )
END

-- --------------------------------
SELECT
  dates.day,
  COUNT(tickets.task_number) AS CountOfOpenTickets
FROM @Dates as dates
LEFT JOIN dbo.wh_task tickets ON (dates.day >= tickets.create_time) AND ((dates.day < tickets.date_completed) OR (tickets.date_completed IS NULL))
GROUP BY dates.day
ORDER BY dates.day DESC