MySQL查询(CustomerID和第1次,第2次和第3次购买的日期)

时间:2015-07-28 03:17:14

标签: mysql northwind

我正在尝试创建一个包含客户ID和第一次,第二次和第三次购买日期的信息中心。我使用MySQL,Northwind db。

我的查询在第一次购买时效果很好,但我不明白如何为每位客户找到第二和第三个购买日期。

现在我正在尝试下一步:2nd_purchase_date是1st_purchase_date之后的下一个MIN(OrderDate),但我收到以下错误'无效使用群组功能'

DROP TABLE IF EXISTS t1;
CREATE TABLE t1
(
    CustomerID varchar(5),
    OrderDate datetime,
    OrderID int,
    i int
);

INSERT INTO t1(CustomerID, OrderDate, OrderID, i)
SELECT CustomerID, min(OrderDate), min(OrderID),1
FROM Orders
GROUP BY CustomerID;

INSERT INTO t1(CustomerID, OrderDate, OrderID, i)
SELECT CustomerID,min(OrderDate), min(OrderID),2
FROM Orders
WHERE min(OrderDate) 
NOT IN 
(
SELECT CustomerID, min(OrderDate), min(OrderID)
FROM Orders
)
GROUP BY CustomerID;

INSERT INTO t1(CustomerID, OrderDate, OrderID, i)
SELECT CustomerID,min(OrderDate), OrderID,3
FROM Orders
WHERE min(OrderDate) 
NOT IN 
(
SELECT CustomerID, min(OrderDate), min(OrderID) FROM Orders
)
GROUP BY CustomerID;

1 个答案:

答案 0 :(得分:0)

如上一个示例here所示,您可以将LIMIT offset, count功能与ORDER BY column ASC结合使用,为单个用户选择具有第二个购买日期的条目(ID为{ XXX 替换为相应的值):

SELECT CustomerID, OrderDate, OrderID
  FROM Orders
  WHERE CustomerID = XXX
  ORDER BY OrderDate ASC
  LIMIT 1, 1;

或第三个购买日期的条目:

SELECT CustomerID, OrderDate, OrderID
  FROM Orders
  WHERE CustomerID = XXX
  ORDER BY OrderDate ASC
  LIMIT 2, 1;

......等等。

您通过

获得第一个条目
SELECT CustomerID, OrderDate, OrderID
  FROM Orders
  WHERE CustomerID = XXX
  ORDER BY OrderDate ASC
  LIMIT 0, 1;

或同等的:

SELECT CustomerID, OrderDate, OrderID
  FROM Orders
  WHERE CustomerID = XXX
  ORDER BY OrderDate ASC
  LIMIT 1;

这应该为您提供单个客户的前三个订单:

SELECT CustomerID, OrderDate, OrderID
  FROM Orders
  WHERE CustomerID = XXX
  ORDER BY OrderDate ASC
  LIMIT 3;

虽然从性能角度来看,以下内容肯定不是很好,但它仍然可以为每个客户提供前三个订单:

SELECT o1.CustomerID, o1.OrderDate, o1.OrderID
  FROM Orders o1
  WHERE o1.OrderID IN
        (SELECT o2.OrderID
           FROM Orders o2
           WHERE o1.CustomerID = o2.CustomerID
           ORDER BY o2.OrderDate ASC LIMIT 3)
  ORDER BY o1.CustomerID, o2.OrderDate ASC;