我有一张表格如下:
CREATE TABLE Activities( Type VARCHAR( 20 ), Assigned_On DATETIME ,Status VARCHAR( 20 ) )
INSERT INTO Activities
VALUES
('Clerical','06/14/2016 11:30:00','Completed')
('Technical','06/14/2016 13:00:00','Completed')
('Clerical','06/14/2016 14:30:00','Completed')
('Technical','06/14/2016 16:00:00','Completed')
('Technical','06/14/2016 17:30:00','Completed')
('Technical','06/14/2016 19:00:00','Completed')
('Clerical','06/14/2016 20:30:00','Completed')
('Technical','06/14/2016 22:00:00','Completed')
('Technical','06/14/2016 23:30:00','Completed')
('Clerical','06/15/2016 01:00:00','Completed')
('Technical','06/15/2016 02:30:00','In Progress')
('Clerical','06/15/2016 04:00:00','In Progress')
('Technical','06/15/2016 05:30:00','In Progress')
('Technical','06/15/2016 07:00:00','In Progress')
('Clerical','06/15/2016 08:30:00','Completed')
('Clerical','06/15/2016 10:00:00','Completed')
('Technical','06/15/2016 11:30:00','Completed')
('Clerical','06/15/2016 13:00:00','Completed')
('Technical','06/15/2016 14:30:00','Completed')
('Technical','06/15/2016 16:00:00','In Progress')
('Technical','06/15/2016 17:30:00','In Progress')
('Clerical','06/15/2016 17:39:00','Waiting')
('Technical','06/15/2016 17:48:00','Completed')
('Technical','06/15/2016 17:57:00','In Progress')
('Clerical','06/15/2016 18:06:00','Waiting')
('Clerical','06/15/2016 18:15:00','Waiting')
('Technical','06/15/2016 18:24:00','Completed')
('Clerical','06/15/2016 18:33:00','Completed')
('Clerical','06/15/2016 18:42:00','In Progress')
('Technical','06/15/2016 18:51:00','In Progress')
('Technical','06/15/2016 19:00:00','Waiting')
('Clerical','06/15/2016 19:09:00','Waiting')
('Technical','06/15/2016 19:18:00','Waiting')
并希望得到等待时间的摘要
Declare @datetimenow datetime
SET @datetimenow = GetDate() -- or some date time to use for testing
Select Count(Type) datediff(Minute, Assigned_On, @datetimenow) where status = 'Waiting'
但是需要按类型分组和列表,每个类型的等待人数和最长等待时间,结果看起来像
Type People Waiting Wait Time (Minutes)
Clerical 5 11:08
Technical 5 15:38
任何想法如何?
感谢
答案 0 :(得分:2)
我不确定我是否理解这个问题,但代码会提出一个想法:
SELECT Type, Count(*) as 'People Waiting',
CAST(DATEDIFF(SECOND,GetDate(), MIN(Assigned_On) ) / 60 as varchar)
+ ':' + CAST(DATEDIFF(SECOND,GetDate(), MIN(Assigned_On) ) % 60 as varchar)
as 'Wait Time (Minutes)'
FROM Activities
WHERE Status = 'Waiting'
GROUP BY Type;
答案 1 :(得分:1)
首先,考虑如何找到“等待的人”和他们的等待时间。我想象这样的事情:
SELECT Type, datediff(minutes, Assigned_on, getdate()) AS WaitMinutes
FROM Activities
WHERE Status = 'Waiting'
现在应该很明显,但你只需使用COUNT(*)
来获取计数,MAX(WaitMinutes)
获得最长等待时间,对吧?如果您不想在WITH
中执行此操作,只需使用公式进行分组:
SELECT Type,
COUNT(*) AS PeopleWaiting,
MAX(datediff(minutes, Assigned_On, getdate())) AS MaxWaitMinutes
FROM Activities
WHERE Status = 'Waiting'
GROUP BY Type