我必须构建一个图表,根据多个过滤器(周,月,自定义日期范围)每天显示数据。
问题在于,在我的数据库中,我只有创建记录的日期,这意味着
where Date >= @start AND Date <= @start
几天内没有记录的行将不会返回。
我希望那几天返回结果为0的行,但我不知道如何在SQL中执行此操作
数据示例
2019-09-13 12:00:43.7761868
2019-09-13 12:01:20.8275512
2019-09-13 21:28:59.3311800
2019-09-13 21:32:12.8601389
2019-09-14 04:37:25.6108193
2019-09-16 13:34:39.7449688
2019-09-16 14:06:18.0098897
2019-09-16 14:59:22.4131463
2019-09-16 15:00:38.8086073
2019-09-17 05:45:06.9280049
2019-09-17 05:45:50.1708972
2019-09-17 13:50:23.9503997
2019-09-17 13:55:13.1940063
2019-09-17 18:40:26.3523765
2019-09-17 18:41:08.2932910
2019-09-18 03:48:59.2092904
2019-09-18 03:49:41.0802705
2019-09-18 06:10:47.0732559
2019-09-18 06:11:30.1833908
请注意,该日期没有记录
2019-09-15
预期结果将是
2019-09-13
2019-09-14
2019-09-15
2019-09-16
2019-09-17
2019-09-18
答案 0 :(得分:1)
年份
SELECT * FROM YourTableName WHERE DATEPART(YEAR, Date_ColumnName) = @Year
一个月
SELECT * FROM YourTableName WHERE DATEPART(MONTH, Date_ColumnName) = @Month
每天
SELECT * FROM YourTableName WHERE DATEPART(DAY, Date_ColumnName) = @Day
自定义日期范围
SELECT * FROM YourTableName
WHERE
convert(DATETIME,Date_ColumnName)
BETWEEN Convert(DATETIME,CASE WHEN isnull(@FromDate,'')='' THEN Date_ColumnName
ELSE isnull(@FromDate,'') END)
AND Convert(DATETIME, CASE WHEN isnull(@ToDate,'')='' THEN Date_ColumnName
ELSE isnull(@ToDate,'') END)
注意:-您可以尝试所有查询...空部分也可以在“自定义日期范围”中处理。....我已经对其进行了测试...
答案 1 :(得分:1)
--Pseudo code for creating a Calendar table using a Common Table Expression (CTE)
--and Custom date range
DECLARE @StartDate datetime,@EndDate datetime
SET @StartDate = '2019-09-13'
SET @EndDate = '2019-09-18'
;WITH CalendarDates(DATEPARAM) AS
(
SELECT @StartDate AS datetime
UNION ALL
SELECT DATEADD(DAY, 1, DATEPARAM)
FROM CalendarDates
WHERE DATEPARAM < @EndDate
)
SELECT CD.DATEPARAM ,count(convert(date,T.testdate)) as records_on_theday
FROM @T T
Right outer join CalendarDates CD on CD.DATEPARAM = convert(date,T.testdate)
Group By convert(date,T.testdate),CD.DATEPARAM
在上面的代码示例中,我们假设搜索基于给定的开始和结束日期(自定义日期范围过滤器)。因此CalendarDates
CTE将给出此范围之间的所有日期。与源表一起使用的Right Outer Join
将给出您希望作为最终输出的记录数。希望这会有所帮助!