0

我从我的函数中获取数据如下:

Date       |   Number
06-02-2012 |    2
06-05-2012 |    5
06-08-2012 |    5

如果我想在以下问题中包含在 DB 中找不到的所有日期,我该怎么做?:

Date       |   Number
06-02-2012 |    2
06-03-2012 |    0
06-04-2012 |    0
06-05-2012 |    5
06-06-2012 |    0
06-07-2012 |    0
06-08-2012 |    5

SELECT convert(varchar, MIN(DATEADD(wk, DATEDIFF(wk, 0, person.date), 0)), 1), Count(person.ID) 
FROM [dbo].[Person] person
WHERE (DATEDIFF(D, person.date, @dateFrom) <=0 AND DATEDIFF(D, person.date, @dateTo) >=0) 
GROUP BY DATEPART(WK, person.date) 
4

3 回答 3

2

您将创建一个临时表或子查询,其中包含所选范围内的所有日期,left join并对源数据使用 a

于 2012-09-10T08:48:51.893 回答
0

我建议您创建一个日期表——一个包含从 2000-01-01 到 2050-12-31 的日期的单列表。然后,您可以在 LEFT JOIN 查询的左侧使用该表,如下所示:

SELECT date_table.date AS [Date], COUNT(your_table.primary_key) AS [Number]
FROM date_table
LEFT JOIN your_table ON date_table.date = your_table.date
WHERE date_table.date BETWEEN '2012-01-01' AND '2012-06-30'

明智地索引日期表,您将得到一个非常有效的查询。

于 2012-09-10T08:54:28.680 回答
0

如果您只需要一个小间隔,您可以尝试这样的功能:

DECLARE @minDate date
DECLARE @maxDate date

SET @minDate = '2012-09-01'
SELECT @maxDate = CAST( CONVERT( CHAR(8), GetDate(), 112) AS DATETIME)


DECLARE @Numbers TABLE(
  Date date,
  Number int)

WHILE @minDate < @maxDate
BEGIN
INSERT INTO @Numbers
SELECT @minDate, 0
WHERE NOT EXISTS( SELECT Number FROM Numbers WHERE [Date] = @minDate )

SET @minDate = DATEADD(day, 1, @minDate)

END

SELECT n.[Date], ISNULL(n.Number, 0) 
FROM @Numbers n
UNION ALL
SELECT Numbers.[Date], ISNULL(Numbers.Number, 0) 
FROM Numbers 
ORDER BY [Date]

If you need more month and year, then I think the best way to make a prefilled permanent helper table with the dates what you need. And make only an easy join on them like it is posted in an other answer.

于 2012-09-10T09:02:44.117 回答