SQL: Count Users with Activity in the Past Week

懵懂的女人 提交于 2019-12-05 13:12:43

I think you just need to add a HAVING clause:

HAVING COUNT(d.[SessionID]) >= 2

On your 10 in 30 query, just change your DATEADD() to have 30 days, and change the HAVING clause to be >= 10.

    SELECT COUNT(d.[SessionID]) AS SessionPastPeriod
        , m.[UserID]
        , m.[Date]
    FROM Sessions_tbl AS m
        INNER JOIN Sessions_tbl as d
            ON m.UserID = d.UserID
            AND d.[Date] <= m.[Date]
            AND d.[Date] > DATEADD(d,-7,m.[Date])
    GROUP BY m.UserID
        , m.[Date]
    HAVING COUNT(d.[SessionID]) >= 2

I hope this helps.

You are too close.

SELECT Count(d.[SessionID]) As SessionPastWeek
      ,m.[UserID]
      ,m.[Date]
FROM [Cosmos].[dbo].[Sessions_tbl] as m
Inner Join [Cosmos].[dbo].[Sessions_tbl] as d on m.[UserID2] = d.[UserID]
--Between does not work here for some reason
where --ADD where clause
d.[Date] <= getdate() AND
d.[Date] > DATEADD(d,-7,getdate())
Group By m.[UserID],m.[Date]
having Count(d.[SessionID])>1 --The magical clause for you.
select  count(*)
from    (
        select  UserID
        ,       sum(case when Date between dateadd(day, -7, getdate()) and getdate()
                    then 1 end) as LastWeek
        ,       sum(case when Date between dateadd(day, -30, getdate()) and getdate()
                    then 1 end) as Last30Days
        from    Sessions_tbl
        group by
                UserID
        ) SubQueryAlias
where   LastWeek >= 2
        or Last30Days >= 10

The following query works:

Select
Count(UserID) As CountUsers
,[Date]
From(  
    SELECT COUNT(d.[SessionID]) AS SessionPastPeriod
        , m.[Date]
        , m.UserID
    FROM [Sessions_tbl] AS m
        INNER JOIN [Sessions_tbl]  as d
            ON m.UserID = d.UserID
            AND d.[Date] <= m.[Date]
            AND d.[Date] > DATEADD(d,-7,m.[Date])
    GROUP BY 
         m.UserID
         ,m.[Date]
    HAVING COUNT(d.[SessionID]) >= 2) SQ
    Group By [Date]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!