我有这个mysql表中的数据:
id customer_id date price
1 A 2014-01-01 4
2 A 2014-02-01 3
3 B 2014-03-01 2.5
4 B 2014-04-01 1
5 B 2014-05-01 5
6 C 2014-06-01 2
7 D 2014-07-01 2
8 D 2014-08-01 2.5
9 D 2014-09-01 1
我想获得customer_id A,B和D的最新两个日期。我的结果应该是这样的:
id customer_id date price
1 A 2014-01-01 4
2 A 2014-02-01 3
4 B 2014-04-01 1
5 B 2014-05-01 5
8 D 2014-08-01 2.5
9 D 2014-09-01 1
非常感谢任何帮助。
答案 0 :(得分:0)
一种可能的方式:
SELECT *
FROM test s
WHERE (
SELECT COUNT(*)
FROM test f
WHERE f.customer_id = s.customer_id AND
f.`date` >= s.`date`
) <= 2
AND customer_id in('A','B','D');
<强> [SQL Fiddle demo] 强>
答案 1 :(得分:-1)
试试这个
select * from table where customer_id in('A','B','D') order by date desc limit 2