这是我的问题。这是一家日光浴沙龙,我们最近增加了水疗服务。客户只需要在一天中晒黑,因此按员工统计不同的客户非常容易。现在,他们在一天中晒黑/水疗超过一次,并在任何一天看到不同的工作人员。我试图将白天的dinstinct客户端数量计算为一个数字。这是查询。我希望这是有道理的。我第一次发布时请原谅我?
此查询将生成每天进入的不同客户端的计数以及员工晒黑的数量。 (这是正确的)我只需要由员工总结一下。如果我不包括日期部分,则会为整个日期范围选择不同的日期部分。
SELECT COUNT(DISTINCT ClientUID) AS [# clients], DATEPART(day, DateOfTan) AS [day of tan], EmployeeUID
FROM History_TanHistory
WHERE DateOfTan > CONVERT(DATETIME, '2016-06-01 00:00:00', 102)
AND DateOfTan < CONVERT(DATETIME, '2016-07-01 00:00:00', 102)
AND Deleted = 0 AND Borrow = 0 AND AddedBack = 0 AND CanceledTan = 0
GROUP BY EmployeeUID, DATEPART(day, DateOfTan)
上述查询产生这种类型的输出(底部没有总和)
EmployeeUID tan of tan#clients
383-E11132012143712J1U 1 52
383-E11132012143712J1U 2 80
383-E11132012143712J1U 3 68
383-E11132012143712J1U 5 58
383-E11132012143712J1U 6 78
383-E11132012143712J1U 7 65
383-E11132012143712J1U 9 85
383-E11132012143712J1U 10 64
383-E11132012143712J1U 11 65
383-E11132012143712J1U 13 55
383-E11132012143712J1U 14 55
383-E11132012143712J1U 16 76
383-E11132012143712J1U 17 65
383-E11132012143712J1U 18 50
383-E11132012143712J1U 20 55
383-E11132012143712J1U 21 56
383-E11132012143712J1U 23 47
383-E11132012143712J1U 24 79
383-E11132012143712J1U 25 59
383-E11132012143712J1U 27 55
383-E11132012143712J1U 28 54
383-E11132012143712J1U 30 62
如果删除了datepart,它会将整个30天期间视为一个分组,并且仅为该员工返回656的非重复计数。
我需要它来返回1383的总和。
上述员工的样本数据。客户端ID可能会在davy中使用服务超过1次,但我只想计算一次。
答案 0 :(得分:1)
如果我理解正确,只需将查询包装为子查询。
这将返回一行,总数为一行。
SELECT
SUM(T.[# clients]) AS TotalClients
FROM
(
SELECT COUNT(DISTINCT ClientUID) AS [# clients], DATEPART(day, DateOfTan) AS [day of tan], EmployeeUID
FROM History_TanHistory
WHERE DateOfTan > CONVERT(DATETIME, '2016-06-01 00:00:00', 102)
AND DateOfTan < CONVERT(DATETIME, '2016-07-01 00:00:00', 102)
AND Deleted = 0 AND Borrow = 0 AND AddedBack = 0 AND CanceledTan = 0
GROUP BY EmployeeUID, DATEPART(day, DateOfTan)
) AS T
如果您希望每个员工SUM
,只需添加另一个GROUP BY
。这将每EmployeeUID
:
SELECT
T.EmployeeUID
,SUM(T.[# clients]) AS ClientsPerEmployee
FROM
(
SELECT COUNT(DISTINCT ClientUID) AS [# clients], DATEPART(day, DateOfTan) AS [day of tan], EmployeeUID
FROM History_TanHistory
WHERE DateOfTan > CONVERT(DATETIME, '2016-06-01 00:00:00', 102)
AND DateOfTan < CONVERT(DATETIME, '2016-07-01 00:00:00', 102)
AND Deleted = 0 AND Borrow = 0 AND AddedBack = 0 AND CanceledTan = 0
GROUP BY EmployeeUID, DATEPART(day, DateOfTan)
) AS T
GROUP BY T.EmployeeUID