3每个客户的最后记录

时间:2014-06-10 18:59:25

标签: mysql sql greatest-n-per-group

我有一个客户表和这样的请求:

客户表:

Key | Name
----+-----------
  1 | Roberto
  2 | Thiago
  3 | Mike 

请求表:

key | Date       | Customer
----+------------+------------  
  1 | 2012-02-07 | 1   
  2 | 2012-02-08 | 2
  3 | 2012-02-09 | 1
  4 | 2012-03-07 | 1
  5 | 2012-03-08 | 3
  6 | 2012-03-09 | 2
  7 | 2012-04-07 | 3
  8 | 2012-04-08 | 1
  9 | 2012-04-09 | 3

我想要一个返回每个客户的最后3个请求的查询。 Obs:我正在使用MySQL服务器

回报应该是这样的:

key | Date       | Customer
----+------------+-----------
  1 | 2012-02-07 | 1
  3 | 2012-02-09 | 1
  4 | 2012-03-07 | 1
  2 | 2012-02-08 | 2
  6 | 2012-03-09 | 2
  5 | 2012-03-08 | 3
  7 | 2012-04-07 | 3
  9 | 2012-04-09 | 3

我无法使用'TOP'命令,因为我使用的是MySQL服务器,而且这个命令只能在SQL Server中使用。

3 个答案:

答案 0 :(得分:0)

我想这应该有效:

SELECT     req.Key,
           req.date,
           req.customer
FROM       [dbo].[Requests] req
INNER JOIN [dbo].[Customers] cust ON cust.CustomerID = req.customerID
GROUP BY   req.Key, req.date, req.customer
ORDER BY   req.date

希望这有帮助!!!

答案 1 :(得分:0)

您可以尝试

select 
r.`key`,
r.Date,
r.customer
from Customers c
left join 
(
  select 
  r1.*
  from Requests r1
  where 
  (
    select count(*)
    from Requests r2
    where r1.customer = r2.customer
    AND r1.`key` <= r2.`key`
  ) <=3
  order by r1.Date desc
)r
on r.customer = c.`key`
order by c.`key`

另一种方式

select
r.`key`,
r.Date,
r.customer
from Customers c
join Requests r on r.`Customer` = c.`key`
where
(
  select count(*) from Customers c1
  join Requests r1 on r1.`Customer` = c1.`key`
  where
  c.`key` = c1.`key`
  and r1.`key`>= r.`key`
) <=3
order by c.`key`,r.Date desc

<强> DEMO

答案 2 :(得分:0)

您可以查看此here

SELECT DISTINCT `key`, date, customer
FROM
(
        SELECT  MAX(r1.`key`) `key`, MAX(r1.date) date, r1.customer customer
        FROM requests r1
        GROUP BY r1.customer
    UNION
        SELECT MAX(r2.`key`) `key`, MAX(r2.date) date, r1.customer customer
        FROM requests r1
        JOIN requests r2 ON  r2.customer = r1.customer
                              AND r2.date < r1.date
        GROUP BY r1.customer
    UNION
        SELECT MAX(r3.`key`) `key`, MAX(r3.date) date, r1.customer customer
        FROM requests r1
        JOIN requests r2 ON  r2.customer = r1.customer
                              AND r2.date < r1.date
        JOIN requests r3 ON r3.customer = r2.customer
                              AND r3.date < r2.date
        GROUP BY r1.customer
) subquery
ORDER BY customer, date, `key`