您需要一个带有日期值的单独表,试试这个
DECLARE @startdate datetime, @enddate datetime
SET @StartDate = CONVERT(varchar(10),DATEADD(day,-7, GETDATE()), 101) + ' 00:00.00';
SET @EndDate = DATEADD(day,7, @StartDate);
;with cte as
(
select @startdate DateValue
union all
select DateValue + 1
from cte
where DateValue + 1 < @enddate
)
select a.DateValue as LoginDate, COUNT(UsersID) AS TotalForDay
from cte a
LEFT outer join [STATS].[dbo].[UsersLogin] b
on CONVERT(varchar(15), a.DateValue,101) = CONVERT(varchar(15), b.[DateTime],101)
group by a.DateValue
order by a.DateValue desc
按小时分组:
DECLARE @startdate datetime, @enddate datetime
SET @StartDate = CONVERT(varchar(10),DATEADD(day,-7, GETDATE()), 101) + ' 00:00.00';
SET @EndDate = DATEADD(day,7, @StartDate);
;with cte as
(
select @startdate DateValue
union all
select DATEADD (hh,1,DateValue)
from cte
where DATEADD (hh,1,DateValue) < @enddate
)
select a.DateValue as LoginDate, COUNT(UsersID) AS TotalForDay
from cte a
LEFT outer join [STATS].[dbo].[UsersLogin] b
on CONVERT(varchar(15), a.DateValue,101) = CONVERT(varchar(15), b.[DateTime],101)
group by a.DateValue
order by a.DateValue desc
OPTION (MAXRECURSION 0)