简体   繁体   中英

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)

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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