每个客户在该特定日期的倒数第五笔交易

Fifth last transaction of each customer on that particular day

我有一个 table,其中包含以下信息:

customer_id | Date | Time| Sales 

我们有一个客户在某一天的多笔交易。如何检索每个客户在任何给定日期的倒数第五笔交易?

试试这个:

SELECT A.customer_id, A.Date, A.Time, A.Sales 
FROM (SELECT A.customer_id, A.Date, A.Time, A.Sales, 
             IF(@customerId = @customerId:=A.customer_id AND @Date = @Date:=A.Date, @Id:=@ID + 1, @ID:=1) AS RowNum
      FROM tableA A, (SELECT @customerId:=0, @Date:='', @Id:=0) AS B 
      ORDER BY A.customer_id, A.Date, A.Time DESC
     ) AS A
WHERE A.RowNum = 5