1

我正在计算UsersID过去 7 天的登录总数()。我计算了此日期范围内的用户 ID 总数并按日期分组。我的问题是,如果某个日期没有记录用户 ID,则不会显示该日期。

所以我需要为没有登录的日期显示 0。

我的代码是:

SET @StartDate = CONVERT(varchar(10),DATEADD(day,-7, GETDATE()), 101) +  ' 00:00.00';
SET @EndDate = DATEADD(day,7, @StartDate);

SELECT CONVERT(DATE, [DateTime]) as LoginDate, COUNT(UsersID) AS TotalForDay
FROM [STATS].[dbo].[UsersLogin]
WHERE [DateTime]>@StartDate 
AND [DateTime]<@EndDate
GROUP BY CONVERT(DATE, [DateTime])
ORDER BY LoginDate desc;
4

3 回答 3

5

您需要一个带有日期值的单独表,试试这个

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) 
于 2013-03-06T14:40:28.113 回答
0

您将需要针对日历关系在日期上进行左连接,无论是作为表静态实现还是作为子查询动态实现。

SET @StartDate = CONVERT(varchar(10),DATEADD(day,-7, GETDATE()), 101) +  ' 00:00.00';
SET @EndDate = DATEADD(day,7, @StartDate);

SELECT C.Date, COUNT(UsersID) AS TotalForDay
FROM Calendar as C
LEFT JOIN [STATS].[dbo].[UsersLogin] as U on C.Date = CONVERT(DATE, [DateTime])       
WHERE [DateTime]>@StartDate 
AND [DateTime]<@EndDate
GROUP BY CONVERT(DATE, [DateTime])
ORDER BY LoginDate desc;
于 2013-03-06T14:41:08.160 回答
0

如果需要比使用这个更简单。创建一个临时表变量并将日期从开始到结束添加到其中:

Declare @temp_Dates Table
(
  TempDate datetime
)

While (@StartDate<@EndDate)
Begin
  Insert Into @temp_Dates Select @EndDate
  Set @EndDate=DATEADD(DAY,-1,@EndDate)
End

之后,将您的表与上面的表左连接:

SELECT Cast(Convert(varchar(20),td.TempDate,101) as DateTime) as LoginDate,     COUNT(UsersID) AS TotalForDay
FROM @temp_Dates td
Left Join  UsersLogin ul On Cast(Convert(varchar(20),ul.DateTime,101) as     DateTime)=Cast(Convert(varchar(20),td.TempDate,101) as DateTime)
GROUP BY Cast(Convert(varchar(20),td.TempDate,101) as DateTime)
ORDER BY LoginDate desc

你会得到你想要的结果。

于 2013-03-06T14:58:40.687 回答