我正在尝试计算在所有日期的30天内,或者在10天内至少有两次会话的用户数。
我的数据如下:
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 query
我在SQL Server 2012中
我在将两者结合起来时遇到了麻烦。
编辑以供澄清:我需要的查询可能没有任何getdate()或类似的,因为我需要知道有多少用户符合1月1日,今天的所有日期以及中间的所有日期。
感谢您的帮助!
答案 0 :(得分:1)
我认为你只需要添加一个HAVING子句:
HAVING COUNT(d.[SessionID]) >= 2
在您的10/30查询中,只需将DATEADD()更改为30天,然后将HAVING子句更改为&gt; = 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
我希望这会有所帮助。
答案 1 :(得分: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.
答案 2 :(得分: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
答案 3 :(得分: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]