0

我想要 GROUP BY 某个列,然后计算用户在一段时间内登录的实例数。

桌子

UserID | LoginDate  | LoginID
1      | 2013-01-03 | 100
1      | 2013-01-05 | 101
1      | 2013-02-04 | 102
2      | 2013-01-03 | 103
2      | 2013-01-05 | 104
2      | 2013-01-04 | 105
3      | 2013-01-03 | 106
3      | 2013-02-05 | 107
3      | 2013-02-04 | 108

输出

UserID | Between 2013-01-31 and 2013-02-31 | Between 2013-02-31 and 2013-02-28 
1      | 2 | 1
2      | 3 | 0
3      | 1 | 2

我试过以下

select UserID, 
       count(case when LoginDate between '2013-01-01' and '2013-01-31' then 1.0 else 0.0 end ),
       count(case when LoginDate between '2013-02-01' and '2013-02-28' then 1.0 else 0.0 end )
from Table
group by UserID

我遇到的问题是最后两列产生的结果与我简单地计算(LoginID)时的结果相同。

4

1 回答 1

1

尝试使用 SUM 而不是 COUNT 即:

select UserID, 
   sum(case when LoginDate between '2013-01-01' and '2013-01-31' then 1 else 0 end ),
   sum(case when LoginDate between '2013-02-01' and '2013-02-28' then 1 else 0 end )
from Table
group by UserID

...而且我认为您不需要使用小数,即。“.0”不应该是必要的。

于 2013-06-17T23:45:29.930 回答