为每个组选择四个项目?

时间:2014-11-21 20:09:02

标签: mysql sql sql-server-2008 join group-by

我有两张桌子,第一张叫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    

我需要改变什么?

2 个答案:

答案 0 :(得分:1)

似乎你想要获得每组的前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

答案 1 :(得分:0)

这是实现它的另一种方式

select 
w.withdrawal_id,
w.card_id,
w.transaction_date
from card c
left join 
(
  select 
  r1.*
  from withdrawal r1
  where 
  (
    select count(*)
    from withdrawal r2
    where r1.card_id = r2.card_id
    AND r1.transaction_date <= r2.transaction_date
  ) <=4
  order by r1.transaction_date desc
)w
on w.card_id = c.card_id
order by c.card_id

<强> demo