在两个日期内获取每周不同的用户数

时间:2017-12-21 07:14:47

标签: sql sql-server

我有一个日志表PRTL_UserAccessLog,其中包含userID,datetime列。我需要在两个自定义日期之间获取每周不同的已记录用户数,如下所示

from date:01 Dec 2017
todate:31 dec 2017

我的星期开始日期应该是星期日。 我创建了以下查询以获得结果

    SET DATEFIRST 7
    SELECT DISTINCT 
       'week '+ CAST(DATEPART(WEEK, Datetime)AS NVARCHAR(10)) AS weeknumber,
   --I need to get the distinct count of users within this week as weekloggedcount
    FROM 
        dbo.PRTL_UserAccessLog
    WHERE
        Datetime > '2017-12-01' AND Datetime < '2017-12-31'
        AND usertypeid=1
    ORDER BY
       weeknumber

结果应该是这样的:

**Weeknumber**   **weeklogcount**
  Week48               10
  Week49               50

1 个答案:

答案 0 :(得分:2)

你可以试试这个。

SET DATEFIRST 7
SELECT DISTINCT 
   'week '+ CAST(DATEPART(WEEK, Datetime)AS NVARCHAR(10)) AS weeknumber,
    COUNT(DISTINCT userID ) weeklogcount
FROM 
    dbo.PRTL_UserAccessLog
WHERE
    Datetime > '2017-12-01' AND Datetime < '2017-12-31'
    AND usertypeid=1
GROUP BY 'week '+ CAST(DATEPART(WEEK, Datetime)AS NVARCHAR(10))
ORDER BY weeknumber