SELECT u.FirstName + ' ' + u.LastName as 'User',
COUNT(*) as 'Number of Calls',
CONVERT(varchar(4), SUM(CASE WHEN c.FromTime BETWEEN @FromDate AND @ToDate
THEN DATEDIFF(mi, c.FromTime, c.ToTime) ELSE 0 END) / 60) + ':' +
CASE WHEN SUM(CASE WHEN c.FromTime BETWEEN @FromDate AND @ToDate
THEN DATEDIFF(mi, c.FromTime, c.ToTime) ELSE 0 END) % 60 < 10 THEN '0' ELSE '' END +
CONVERT(varchar(2), SUM(DATEDIFF(mi, c.FromTime, c.ToTime)) % 60) as 'Total Time Spent',
CONVERT(varchar(4), AVG(DATEDIFF(mi, c.FromTime, c.ToTime)) / 60) + ':' +
CASE WHEN AVG(DATEDIFF(mi, c.FromTime, c.ToTime)) % 60 < 10 THEN '0' ELSE '' END +
CONVERT(varchar(2), AVG(DATEDIFF(mi, c.FromTime, c.ToTime)) % 60) as 'Average Call Time'
FROM Calls c
JOIN Users u ON u.UserID = c.TakenBy
WHERE c.FromTime BETWEEN @FromDate AND @ToDate
GROUP BY u.UserID, u.FirstName, u.LastName
ORDER BY u.FirstName + ' ' + u.LastName
前面的SQL查询返回正确的“调用次数”,但“总时间”和“平均时间”始终相同,无论调用次数多少(显然都是错误的)。
我已阅读并尝试使用CASE WHEN __然后在SUM内部对ELSE 0进行实现,但它仍然返回不正确的值。
我可以获得此查询以返回正确结果的唯一方法是,如果我完全删除所有其他信息,例如
SELECT SUM(DATEDIFF(mi, FromTime, ToTime)) FROM Calls WHERE c.FromTime BETWEEN...
我如何仍然使用我的JOIN和GROUP BY并获得聚合函数来给我想要的结果?
感谢您的帮助!
答案 0 :(得分:1)
你可能最好使用子查询,例如在SELECT部分中,添加(SELECT SUM(...) FROM ... WHERE ...) AS total_sum
。