SQL:包含用户计数的每日报告

时间:2016-10-04 09:50:48

标签: sql sql-server

我正在尝试获取用户的30天报告,该报告将返回日期用户总数作为在此处创建的计数日期,我用这个查询做了

 Select count(*)  As [Count] ,  
        (SELECT CONVERT(date, AddDate)) As [Date] 
 from Users 
 WHERE AddDate  >= (SELECT DateAdd(month, -1, Convert(date, GetDate()))) 
 Group By CONVERT(date, AddDate)

它只给我创建任何用户的日期,但我想显示所有 30天,如果它有计数 0

同样的情况我想用月度报告。 我正在创建用户创建的几个月,现在我想将其更改为从本月开始过去12个月以及总用户数。为此我正在使用此查询

 Select count(*)  As [Count] ,
        (Select DATEPART( month , DateAdd( month , DATEPART(mm,AddDate) , -1 ) )) as Month
 from Users 
 WHERE AddDate  >= (SELECT DateAdd(YEAR, -1, Convert(date, GetDate())))
 Group By DATEPART(mm,AddDate)

5 个答案:

答案 0 :(得分:3)

使用日历CTE:

With NumberSequence ( Number ) as
(
    Select 1 as Number
    union all
    Select Number + 1
    from NumberSequence
    where Number <= 30
)
, CalendarCTE as
(
    select cast(dateadd(dd, -30 + Number,getdate()) as Date) as CalDate
    from Numbersequence
)

select CalDate, count(U1.*) as CountUsers
from CalendarCTE
left join Users U1
on CalDate = convert(date, U1.AddDate)
group by CalDate

答案 1 :(得分:2)

正如我在评论中提到的,您需要Calendar tableLeft Join

SELECT Count(u.adddate) AS [Count], 
       c.dates  AS [Date] 
FROM   calendar_table C 
       LEFT JOIN users U 
              ON c.dates = CONVERT(DATE, adddate) 
WHERE  c.dates >= Dateadd(month, -1, CONVERT(DATE, Getdate())) 
GROUP  BY c.dates 

要生成/创建日历表或日期,请查看以下问题

How to generate a range of dates in SQL Server

Generate Dates between date ranges

How to create a Calender table for 100 years in Sql

答案 2 :(得分:2)

试试这个脚本:

WITH CTEDates
AS
(
  SELECT CAST(GetDate() as date) AS [date]
  UNION ALL
  SELECT DATEADD(dd, 1, [date])
  FROM CTEDates
  WHERE DAY([date]) <= 30
)
Select count(*)  As [Count] ,CONVERT(date, AddDate) As [Date] 
from CTEDates 
LEFT JOIN Users ON CTEDates.date=CONVERT(date, AddDate)
WHERE AddDate  >= DateAdd(month, -1, GetDate())
Group By CONVERT(date, AddDate)

答案 3 :(得分:1)

您可以使用CTE获取30天的日历。然后将您的Users表连接到它。

DECLARE @CurrentTime DATETIME = GETDATE()
;WITH CTE AS
    (
      SELECT CONVERT(DATE, @CurrentTime) AS [Date]

      UNION ALL

      SELECT  DATEADD(dd, -1, Date)
      FROM    CTE
      WHERE   DATEADD(dd, 29, Date) > @CurrentTime
    )
SELECT COUNT(U.AddDate) AS [Count]
, CTE.[Date] AS [Date]
FROM CTE
LEFT JOIN users U
ON CTE.Date = CONVERT(Date, AddDate)
GROUP BY CTE.Date

您可以使用类似的CTE获取十二个月的日历并使用相同的联接来计算。

HTH。

答案 4 :(得分:1)

toLowerCase