我有两个表,第一个表名为card

| card_id | card_name |


和表withdrawal

| withdrawal_id | card_id | transaction_date |


我想获取每个card_id的最后四个transaction_dates。

我尝试了这段代码,但它没有给出最后4个日期:

SELECT a.card_id, b.transaction_date
FROM card AS a
JOIN withdrawal AS b ON a.card_id = b.card_id
GROUP BY a.card_id, b.transaction_date
ORDER BY a.card_id, b.transaction_date


我需要更改什么?

最佳答案

似乎您想获得每个组的前N行,可以使用以下方法完成此操作:

SELECT a.card_id, b.transaction_date
FROM card a
JOIN withdrawal b ON a.card_id = b.card_id
WHERE(
   SELECT COUNT(*)
   FROM card c
   JOIN withdrawal w ON w.card_id = c.card_id
   WHERE c.card_id = a.card_id AND w.transaction_date <= b.transaction_date
) <= 4
ORDER BY a.card_id, b.transaction_date


有关获取每个组的行的更多信息,请参见此question

关于mysql - 为每个组选择四个项目?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27069453/

10-09 09:48