今天是客户的第一个订单周年纪念日吗?
Is Today the Customer's First Order Anniversary?
我正在尝试使用 MySQL 查询来查看今天是否是客户的第一个订单日期。我正在查看单个数据库 table - tblOrders
到目前为止,我的尝试导致退回的订单恰好落在今天的某个时间,但不是他们的 'first' 订单。
SELECT FirstName, LastName, Email, COUNT(OrderID) AS NumberOfOrders, CreateDate
FROM tblOrders
WHERE (MONTH(CreateDate) = MONTH(NOW())
AND DAY(CreateDate) = DAY(NOW()))
GROUP BY Email
ORDER BY CreateDate
我觉得我需要一个子查询,但我正在转动轮子。
如果你想要客户的第一个订单,你需要使用 MIN(CreateDate)
,但是聚合不能出现在 WHERE
它们必须出现在 HAVING
,所以你的查询将是:
SELECT o.FirstName,
o.LastName,
o.Email,
COUNT(o.OrderID) AS NumberOfOrders,
MIN(o.CreateDate) AS FirstOrder
FROM tblOrders AS o
GROUP BY o.FirstName, o.LastName, o.Email
HAVING MONTH(MIN(o.CreateDate)) = MONTH(NOW())
AND DAY(MIN(o.CreateDate)) = DAY(NOW());
你的问题是你的计数将只计算与今天相同 month/day 的订单,而不是该客户的所有订单,所以如果你只想知道客户详细信息很好,但是如果您需要该客户的订单总数,您将需要一个子查询(如您所想):
SELECT o.FirstName, o.LastName, o.Email, o.NumberOfOrders, o.FirstOrder
FROM (
SELECT o.FirstName,
o.LastName,
o.Email,
MIN(o.CreateDate) AS FirstOrder,
COUNT(*) AS NumberOfOrders
FROM tblOrders AS o
GROUP BY o.FirstName, o.LastName, o.Email
) AS o
WHERE MONTH(o.FirstOrder) = MONTH(NOW())
AND DAY(o.FirstOrder) = DAY(NOW());
WITH cte AS (
SELECT *, MIN(CreateDate) OVER (PARTITION BY Email) CreateDate
FROM tblOrders
)
SELECT FirstName, LastName, Email, COUNT(DISTINCT OrderID) AS NumberOfOrders, CreateDate
FROM cte
WHERE DATE_FORMAT(CreateDate, '%m%d') = DATE_FORMAT(CURRENT_DATE, '%m%d')
GROUP BY FirstName, LastName, Email, CreateDate
我正在尝试使用 MySQL 查询来查看今天是否是客户的第一个订单日期。我正在查看单个数据库 table - tblOrders
到目前为止,我的尝试导致退回的订单恰好落在今天的某个时间,但不是他们的 'first' 订单。
SELECT FirstName, LastName, Email, COUNT(OrderID) AS NumberOfOrders, CreateDate
FROM tblOrders
WHERE (MONTH(CreateDate) = MONTH(NOW())
AND DAY(CreateDate) = DAY(NOW()))
GROUP BY Email
ORDER BY CreateDate
我觉得我需要一个子查询,但我正在转动轮子。
如果你想要客户的第一个订单,你需要使用 MIN(CreateDate)
,但是聚合不能出现在 WHERE
它们必须出现在 HAVING
,所以你的查询将是:
SELECT o.FirstName,
o.LastName,
o.Email,
COUNT(o.OrderID) AS NumberOfOrders,
MIN(o.CreateDate) AS FirstOrder
FROM tblOrders AS o
GROUP BY o.FirstName, o.LastName, o.Email
HAVING MONTH(MIN(o.CreateDate)) = MONTH(NOW())
AND DAY(MIN(o.CreateDate)) = DAY(NOW());
你的问题是你的计数将只计算与今天相同 month/day 的订单,而不是该客户的所有订单,所以如果你只想知道客户详细信息很好,但是如果您需要该客户的订单总数,您将需要一个子查询(如您所想):
SELECT o.FirstName, o.LastName, o.Email, o.NumberOfOrders, o.FirstOrder
FROM (
SELECT o.FirstName,
o.LastName,
o.Email,
MIN(o.CreateDate) AS FirstOrder,
COUNT(*) AS NumberOfOrders
FROM tblOrders AS o
GROUP BY o.FirstName, o.LastName, o.Email
) AS o
WHERE MONTH(o.FirstOrder) = MONTH(NOW())
AND DAY(o.FirstOrder) = DAY(NOW());
WITH cte AS (
SELECT *, MIN(CreateDate) OVER (PARTITION BY Email) CreateDate
FROM tblOrders
)
SELECT FirstName, LastName, Email, COUNT(DISTINCT OrderID) AS NumberOfOrders, CreateDate
FROM cte
WHERE DATE_FORMAT(CreateDate, '%m%d') = DATE_FORMAT(CURRENT_DATE, '%m%d')
GROUP BY FirstName, LastName, Email, CreateDate