4

我正在尝试计算在所有日期的 7 天内或 30 天内至少有两次会话的用户数量。

我的数据如下:

Date        UserID  SessionID 
1/1/2013    Bob1234    1
2/1/2013    Bob1234    2
2/2/2013    Bob1234    3
2/3/2013    Cal5678    4

这将导致下表(仅显示选择日期)

Date    CountActiveUsers
1/1/2013    1
1/15/2013   0
2/2/2013    1
2/3/2013    2

真实数据集具有连续数据范围内所有日期的值,结果表应具有每个日期的条目。

SessionID 是唯一的,并且 UserID 总是指同一个人。

到目前为止,我有两个查询可以做一些接近的事情。第一个返回用户在过去一周内的会话数:

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] AND 
--Between does not work here for some reason
d.[Date] <= m.[Date] AND
d.[Date] > DATEADD(d,-7,m.[date])

  Group By m.[UserID]
      ,m.[Date]

另一个来自以下链接,该链接计算给定日期 Active Users SQL 查询中的活动用户数

我在 SQL Server 2012

我很难将两者结合起来。

编辑澄清:我需要的查询可能没有任何 getdate() 或类似的,因为我需要知道有多少用户符合今天 1 月 1 日的“活动”标准,以及其间的所有日期。

谢谢你的帮助!

4

4 回答 4

1

我认为您只需要添加一个 HAVING 子句:

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

在 10 in 30 查询中,只需将 DATEADD() 更改为 30 天,并将 HAVING 子句更改为 >= 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

我希望这有帮助。

于 2013-05-23T18:41:41.723 回答
0

你离得太近了。

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.
于 2013-05-23T07:54:20.603 回答
0
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
于 2013-05-23T07:54:21.700 回答
0

以下查询有效:

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]
于 2013-05-25T00:14:38.557 回答