简体   繁体   English

我需要一个查询来为SQL Server 2005中每个不同的时间戳计算用户实例的数量

[英]I need a query to count the number of user instances for each distinct timestamp in SQL Server 2005

Here is my data table: 这是我的数据表:

userid  timestamp
------------------------
user1   2017-08-15 17:00
user1   2017-08-15 17:00
user1   2017-08-15 17:00
user2   2017-08-15 17:00
user2   2017-08-15 17:00
user3   2017-08-15 17:00
user1   2017-08-15 18:00
user1   2017-08-15 18:00
user2   2017-08-15 18:00
user2   2017-08-15 18:00
user2   2017-08-15 18:00
user3   2017-08-15 18:00

I want the result to look like this: 我希望结果看起来像这样:

userid    countoftimestamp
-----------------------------
user1     3_2017-08-15 17:00
user2     2_2017-08-15 17:00
user3     1_2017-08-15 17:00
user1     2_2017-08-15 18:00

and so on. 等等。

SELECT userid, timestamp, count(*)
FROM datatabable
GROUP BY  userid, timestamp

You may notice that I used varchar(16) to truncate your timestamp down to minutes (excluding seconds and milliseconds) 您可能会注意到,我使用varchar(16)将时间戳截断为分钟(不包括秒和毫秒)

Example

Select userid
      ,countoftimestamp = cast(sum(1) as varchar(25))+'_'+convert(varchar(16),timestamp,20)
 From  YourTable
 Group By userid,convert(varchar(16),timestamp,20)

Returns 退货

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM