MS-Access Including all days in a Date Range Query

醉酒当歌 提交于 2019-12-09 01:02:23
HansUp

This could be fairly easy with a calendar table. You can build your own using custom CreateTable_calendar and LoadCalendar procedures.

Create a query which filters the calendar table based the the date range and LEFT JOIN it to your other table. (I simplified the SELECT field list in this example.)

SELECT
    c.the_date,
    Count(ddb.Date) AS [# Discharges]
FROM
    tblCalendar AS c
    LEFT JOIN DischargeDatabase AS ddb
    ON c.the_date = ddb.Date
WHERE
    c.the_date Between
            Forms!QueryForm!TextCriteriaQ0A
        And Forms!QueryForm!TextCriteriaQ0B
GROUP BY c.the_date;

You are on the right track with your last statement! This kind of thing - fill all the groups even when there is no data - can be done with what we call a numbers table or tally table, which can be a CTE, or a real table, whatever you want to do. You can expand the CTE to generate dates...

;WITH CTE AS (
  SELECT 1 as Num
  UNION ALL
  SELECT Num + 1 FROM CTE WHERE Num < @Max
)

SELECT * FROM CTE

This pattern can be expanded to generate your dates...

declare @startDate datetime
set @startDate = getdate() --to start from today

;WITH CTE AS (
  SELECT @startDate as myDate
  UNION ALL
  SELECT dateadd(day, 1, myDate) as myDate FROM CTE WHERE myDate < dateadd(day, 30, @startDate)
)

SELECT myDate FROM CTE

Now, you can use that CTE as the left table in a right outer join. In Access, I think this will need to be a real table. Just create one and manually populate it with numbers - you only have to do this one time.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!