我有一个用于存储用户记录的表
这包括列username
,FromDate
,ToDate
,Status
我需要在1 Dec 2010
和1 April 2011
上找到活跃用户的数量(状态)。
换句话说,我们正在尝试确定1 Dec 2010
和1 Apr 2011
上有多少用户处于有效状态,以便我们可以比较已添加/丢失的用户数量。
如何做到这一点?
答案 0 :(得分:3)
12月1日和4月1日均有效的用户:
with cte
as
(
select UserName, FromDate, ToDate
from MyTable
where Status = 'Active' -- adjust to your status type
)
select distinct UserName
from cte
where
FromDate < '20101202'
and ToDate >= '20101201' and
UserName in
(
select *
from cte
where FromDate < '20110402' and ToDate >= '20110401'
)
要查看添加了哪些用户以及删除了哪些用户,您可以执行以下操作:
with cte
as
(
select UserName, FromDate, ToDate
from MyTable
where Status = 'Active' -- adjust to your status type
)
select UserName, sum(WasActiveOnDecFirst) WasActiveOnDecFirst, sum(WasActiveOnAprFirst) WasActiveOnAprFirst
from
(
select
isnull(du.UserName, au.UserName) UserName,
case when du.UserName is null then 0 else 1 end WasActiveOnDecFirst,
case when au.UserName is null then 0 else 1 end WasActiveOnAprFirst
from
(
select distinct UserName
from cte
where FromDate < '20101202' and ToDate >= '20101201'
) du
full join
(
select distinct UserName
from cte
where FromDate < '20110402' and ToDate >= '20110401'
) au
on du.UserName = au.UserName
) tt
group by UserName
with rollup
结果如下:
UserName WasActiveOnDecFirst WasActiveOnAprFirst
-------------------- ------------------- -------------------
user1 1 1
user2 1 1
user3 1 1
user4 0 1
NULL 3 4
最后一行是总用户数。
答案 1 :(得分:2)
declare @FromDate date = '20101201'
declare @ToDate date = '20110401'
select
count(case when @FromDate between FromDate and ToDate then 1 end) as CountFromDate,
count(case when @ToDate between FromDate and ToDate then 1 end) as CountToDate
from YourTable
where FromDate <= @ToDate and
ToDate >= @FromDate and
Status = 1
答案 2 :(得分:1)
编辑:请参阅Mikael Eriksson提供的答案。它看起来比我写的查询要好得多。
如果你只有两个比较日期,你可以这样做。屏幕截图# 1 显示针对示例数据的以下给定查询的输出。用户1
,4
,6
和9
在 2010-12-01
上有效。用户1
,3
,4
,5
,7
和8
在 2011-04-01
。因此,计数 4 和 6 。
DECLARE @Date1 DATETIME
DECLARE @Date2 DATETIME
SET @Date1 = '2010-12-01'
SET @Date2 = '2011-04-01'
SELECT @Date1 AS AsOnDate
, COUNT(Username) AS ActiveCount
FROM dbo.Users
WHERE @Date1 BETWEEN FromDate AND ToDate
UNION
SELECT @Date2 AS AsOnDate
, COUNT(Username) AS ActiveCount
FROM dbo.Users
WHERE @Date2 BETWEEN FromDate AND ToDate
希望有所帮助。
屏幕截图#1: