如何计算工作天数?

时间:2017-04-05 13:11:35

标签: sql sql-server tsql

我在SQL Server 2008中有一个表,其中包含以下数据:

user ,number of request, date number of request

user1, ID1139151, 2017-03-15 13:10:01.000

user1, ID1139152, 2017-03-13 14:31:05.000

user2, ID1139153, 2017-03-16 10:38:08.000

user2, ID1139154, 2017-03-16 09:26:04.000

user2, ID1139155, 2017-03-17 18:09:15.000

user2, ID1139156, 2017-03-17 20:14:29.000

user2, ID1139157, 2017-03-28 11:18:18.000

帮助我在SQL查询的帮助下找到每个用户的天数。

Result:

user, date number of request

user1, 2

user2, 3

创建数据的脚本:

CREATE TABLE Mytable (

   [user] varchar(50) NOT NULL,

   [number of request] varchar(15) NOT NULL,

   [date_number_of_request] datetime NOT NULL,     )


INSERT INTO Mytable  

VALUES 

('user1','ID1139151','2017-03-15 13:10:01.000'),

('user1','ID1139152','2017-03-13 14:31:05.000'),

('user2','ID1139153','2017-03-16 10:38:08.000'),

('user2','ID1139154','2017-03-16 09:26:04.000'),

('user2','ID1139155','2017-03-17 18:09:15.000'),

('user2','ID1139156','2017-03-17 20:14:29.000'),

('user2','ID1139157','2017-03-28 11:18:18.000');

3 个答案:

答案 0 :(得分:2)

使用count(distinct col)并将日期时间截断为dateadd(day,datediff(day, 0, [date_number_of_request]), 0)

select [user]
    , DaysWithRequests = count(distinct 
        dateadd(day,datediff(day, 0, [date_number_of_request]), 0)
        )
from mytable
group by [user]

使用convert(date,[date_number_of_request])

的相同查询
select [user]
    , DaysWithRequests = count(distinct convert(date,[date_number_of_request]))
from mytable
group by [user]

rextester演示:http://rextester.com/EMKMK22273

返回:

+-------+------------------+
| user  | DaysWithRequests |
+-------+------------------+
| user1 |                2 |
| user2 |                3 |
+-------+------------------+

答案 1 :(得分:1)

也许做这样的事情:

 SELECT users, COUNT(DISTINCT CAST(date_number_of_request AS date))
 FROM mytable 
 GROUP BY users

答案 2 :(得分:1)

对于每个用户,您似乎想要date_number_of_request列中不同日期的数量?

select user, count(distinct convert(date, date_number_of_request))
  from myTable
 group by user