SQL 服务器:按用户和日期分组计数

SQL Server: Count grouping by user and date

在我的 SQL Server 2008 中,我有一个 table 存储每个用户操作的 datetime。它看起来像这样:

id  |  username   |   action  |  actionDate
------------------------------------
1   |  bob        |   add     |  2015-08-15 11:20:12
2   |  bob        |   add     |  2015-08-15 11:21:52
3   |  sandra     |   add     |  2015-08-15 11:25:32
4   |  sandra     |   add     |  2015-08-15 11:26:32
5   |  bob        |   add     |  2015-08-15 11:31:52
6   |  sandra     |   add     |  2015-08-16 13:46:32
7   |  sandra     |   add     |  2015-08-16 13:26:32
8   |  bob        |   add     |  2015-08-16 13:31:52
9   |  sandra     |   add     |  2015-08-16 13:46:32

这个 table 相当大,可以存储很多很多天的数据。所以我需要了解每个用户每天执行操作 "add" 的次数。例如:

actionDate   |  username   |   countRow
2015-08-15   |  bob        |   3
2015-08-15   |  sandra     |   2
2015-08-16   |  bob        |   2
2015-08-16   |  sandra     |   3

我已经尝试了很多不同的查询,但我仍然无法得到它。我认为最接近的查询如下所示:

SELECT S.username, S.actionDate, C.countRow
    From dbo.actionTable S
    INNER JOIN( SELECT Convert(date, actionDate),count(username) as countRow
                FROM dbo.actionTable
                WHERE action = 'add'
                GROUP BY Convert(date, actionDate)) C ON S.actionDate = C.actionDate

但是这个查询returns我错误的数据太多了。请告诉我哪里错了。

为什么不直接做..

select 
  username
  ,convert(date,actionDate) as actionDate
  ,count(*) as countRow
from actionTable
where action = 'add'
group by username
         ,convert(date,actionDate)

尝试

select convert(date,actionDate) actionDate, username, 
count(*) coutntRow from actionTable 
where action   = 'add'
group by convert(date,actionDate), userName
SELECT S.username,  Convert(date, S.actionDate), count(S.id) as  countRow,S.action
From dbo.actionTable S  WHERE S.action = 'add' 
GROUP BY Convert(date, S.actionDate),S.action,S.username
I recommend you the normalization of your database.

If I were you I do this: 
++++++++++++++++++++++++
Table name: **userTable**
------------------------------------
id |  username 
------------------------------------
1  | bob        
2  | sandra 
3  | peter
++++++++++++++++++++++++
Table name: **actionTable**
------------------------------------
id | action
------------------------------------
1  | add
2  | update
3  | delete 
++++++++++++++++++++++++
Table name: **actionUser**
------------------------------------
ID  | user_id  | action_id |  actionDate
------------------------------------
| 1 |  1       |   1       | 2015-08-15 11:20:12
| 2 |  2       |   2       | 2015-08-15 11:21:52
| 3 |  1       |   1       | 2015-08-15 11:25:32 

这是解决此问题的更好架构。

查询应该是这样的:

SELECT COUNT(user_id)
FROM dbo.actionUser
WHERE user_id = %

其中 % 是您的用户 ID。