我使用以下查询来计算每月每天访问该网点的员工总数,以便输出如下所示
Outlet 12/01/2017 12/02/2017 -- rest days of the month
Outlet1 6 5
Outlet2 4 3
但问题是我有一些重复的值,所以我必须使用count distinct 在下面的查询中,但它给出以下错误
第15行,第1行,第1行,第1行 关键字' distinct'附近的语法不正确。
请注意,如果我删除了不同的查询工作正常
查询
DECLARE @cols AS nvarchar(max),
@query AS nvarchar(max)
SELECT
@cols = STUFF((SELECT
',' + QUOTENAME(LogDate)
FROM dbo.AccessLog
WHERE month(CONVERT(datetime,LogDate)) = 12
and year(CONVERT(datetime,LogDate)) = 2017
and AccessLog.InOut = 0
GROUP BY LogDate
ORDER BY LogDate
FOR xml PATH (''), TYPE)
.value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET @query = 'SELECT abr as Outlet,' + @cols +
' from (select abr,LogDate,TerminalID,EmployeeID
from AccessLog
INNER JOIN dbo.Outlet
ON dbo.Outlet.Code = dbo.AccessLog.TerminalID
where AccessLog.InOut=0
and month(CONVERT(datetime,LogDate)) = ''12''
and year(CONVERT(datetime,LogDate)) = ''2017'') x
pivot (count(distinct EmployeeID)
for LogDate in (' + @cols + ') ) p '
EXECUTE (@query);