计算实例数,并在按另一列分组时将它们放入列中

时间:2013-06-17 23:29:57

标签: mysql sql group-by

我希望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)时的结果相同。

1 个答案:

答案 0 :(得分: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”不是必需的。