SQL Server:按用户和日期计数分组

时间:2015-08-24 06:33:03

标签: sql-server tsql count

在我的SQL Server 2008中,我得到了一个存储每个用户操作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

这张表相当大,可以存储很多天的数据。所以我需要知道每个用户每天为“添加”操作多少次。 e.g:

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

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

4 个答案:

答案 0 :(得分:0)

为什么不直接这样做..

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

答案 1 :(得分:0)

尝试

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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。