我正在尝试为每个CSR登录数小时。
我尝试运行以获取数据的查询是:
SELECT T1.user_log_id,
T1.[user],
min(T1.event_date) AS Date1,
max(T2.event_date) AS Date2,
DATEDIFF(hour, T1.event_date, T2.event_date) AS DaysDiff
FROM leads.dbo.lds_User_log T1
JOIN leads.dbo.lds_User_log T2
ON T1.user_log_id = T2.user_log_id
--AND T2.event_date >= T1.event_date
WHERE T1.event_date between '2018-05-18 00:00:01' AND '2018-05-18 23:00:01'
GROUP BY T1.user_log_id, T1.event_Date, T2.event_date, T1.[user];
在表格中我们有:
老实说,我不知道如何将数据输入到自身中以从DB中提取LOGIN和LOGOUT事件以正确运行DATEDIFF,并且合法丢失。答案 0 :(得分:2)
您遇到的问题是您正在计算组中使用的元素的最大值或分钟数。您应该从组中删除它们。如果你不能使用Date1& diff中的Date2变量,这取决于您执行此查询的数据库,您无法通过在FROM和JOIN中使用预先计算的表来尝试它。
您可以尝试以下解决方案:
SELECT T1.user_log_id,
T1.[user],
min(T1.event_date) AS Date1,
max(T2.event_date) AS Date2,
DATEDIFF(hour, Date1, Date2) AS DaysDiff
FROM leads.dbo.lds_User_log T1
JOIN leads.dbo.lds_User_log T2
ON T1.user_log_id = T2.user_log_id
WHERE T1.event_date between '2018-05-18 00:00:01' AND '2018-05-18 23:00:01'
GROUP BY T1.user_log_id, T1.[user];
如果变量不能在同一个选择中使用,则无法通过这种方式解决:
SELECT T1.user_log_id,
T1.[user],
T1.MinEventDate,
T2.MaxEventDate,
DATEDIFF(hour, T1.MinEventDate, T2.MaxEventDate) AS DaysDiff
FROM (SELECT user_log_id,[user],min(event_date) as MinEventDate
FROM leads.dbo.lds_User_log
WHERE event_date between '2018-05-18 00:00:01' AND '2018-05-18 23:00:01'
GROUP BY user_log_id,[user]) T1
JOIN (SELECT user_log_id,[user],max(event_date) as MaxEventDate
FROM leads.dbo.lds_User_log
WHERE event_date between '2018-05-18 00:00:01' AND '2018-05-18 23:00:01'
GROUP BY user_log_id,[user]) T2
ON T1.user_log_id = T2.user_log_id
GROUP BY T1.user_log_id, T1.[user];
希望这有帮助!