我需要按日期对日志表中的记录进行分组,并在该特定日期对由regrular员工或specialEmployee进行访问的次数进行分组。访问应该是不同的,例如,如果用户类型登录两次,那么它应该只计算当天一次
Type
PK typeId
name
Employee
PK empId
firstName
lastName
FK typeId
Log
PK logId
FK empId
date
我已尝试过以下查询,但无济于事。当我用计数替换sum / case时它可以工作但是我无法明确指定哪种类型的用户
SELECT L.`date`
SUM(DISTINCT CASE WHEN E.typeId =1 THEN 1 ELSE 0 END) as specialEmployeeAccesses,
SUM(DISTINCT CASE WHEN E.typeId=2 THEN 1 ELSE 0 END) as regularEmployeeAccesses
FROM LOG L
INNER JOIN
Employee E
ON E.empId = L.empId
GROUP BY L.`date`
答案 0 :(得分:1)
尝试:
SELECT L.`date`,
COUNT(DISTINCT CASE WHEN E.typeId=1 THEN E.empId END)
as specialEmployeeAccesses,
COUNT(DISTINCT CASE WHEN E.typeId=2 THEN E.empId END)
as regularEmployeeAccesses
FROM LOG L
INNER JOIN Employee E
ON E.empId = L.empId
GROUP BY L.`date`