我有此查询需要更正。所以现在我有90%的需求,但是最后一步给我带来了麻烦。我知道在1996-07-04年,第5名员工第一次访问了我的网站,并且正确地获得了第一个计时器的计数。1996年7月11日,我知道第5名员工再次访问了该网站,但我们不想再次数他。
SELECT
Orders.OrderDate,
COUNT(OrderDetails.OrderDetailID) AS NumSessions,
COUNT(DISTINCT Orders.EmployeeID)
FROM OrderDetails
LEFT JOIN Orders
ON OrderDetails.OrderID=Orders.OrderID
GROUP BY Orders.OrderDate
EXPECTED:
DATE NumSessions FirstTimers
1996-07-04 3 1
1996-07-11 3 0
ACTUAL:
DATE NumSessions FirstTimers
1996-07-04 3 1
1996-07-11 3 1
答案 0 :(得分:0)
也许是这样(尽管我不能保证它在语法上是正确的):
SELECT
Orders.OrderDate,
COUNT(OrderDetails.OrderDetailID) AS NumSessions,
COUNT(DISTINCT Orders.EmployeeID WHERE Orders.OrderDate = (
SELECT MIN(b.OrderDate) FROM Orders b WHERE Orders.EmployeeID = b.EmployeeID)
)
FROM OrderDetails
LEFT JOIN Orders
ON OrderDetails.OrderID=Orders.OrderID
GROUP BY Orders.OrderDate
但是我不知道这将如何影响性能。 :)
答案 1 :(得分:0)
这有点复杂。一种方法是使用子查询来计算一阶日期并将其用于逻辑中:
SELECT o.OrderDate,
COUNT(od.OrderDetailID) AS NumSessions,
SUM( o.OrderDate = oe.FirstOrderDate ) as FirstTimers
FROM Orders o LEFT JOIN
OrderDetails od
ON O.OrderId = od.OrderId LEFT JOIN
(SELECT o.EmloyeeID, MIN(OrderDate) as FirstOrderDate
FROM Orders o
GROUP BY OrderDate
) o
ON oe.EmployeeId = o.EmployeeId
GROUP BY o.OrderDate