每个客户在该特定日子的最后一笔交易

时间:2015-01-07 09:27:59

标签: mysql sql select sql-order-by row-number

我有一张表格,其中包含以下信息:

customer_id | Date | Time| Sales 

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

1 个答案:

答案 0 :(得分:0)

试试这个:

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