1

I can't solve this on MS Access SQL.

I have a foo table with this fields: id, title, category, date

I need to show 6 records showing the 2 most recent items from each category

For example, I have:

ID   TITLE   CAT   DATE
------------------------
1    aaa     cat1  12/03/12  
2    sdfs    cat2  12/03/12  
3    asg     cat2  13/03/12  
4    flkgjfl cat3  11/03/12  
5    dgdg    cat1  18/03/12  
6    dfgd    cat1  15/03/12  
7    dgdgd   cat3  18/03/12  
8    dfgd    cat3  12/03/12  
9    uiuou   cat1  14/03/12  
10   ghj     cat4  11/03/12  

So, I need something like:

ID      TITLE   CAT     DATE
----------------------------------
5   dgdg    cat1    18/03/2012  
6   dfgd    cat1    15/03/2012  
3   asg cat2    13/03/2012  
2   sdfs    cat2    12/03/2012  
7   dgdgd   cat3    18/03/2012  
8   dfgd    cat3    12/03/2012  

Thank you in advance.

Vikram
  • 8,235
  • 33
  • 47
Jaume
  • 13
  • 3

1 Answers1

1

How about this, cat is the name of the table.

SELECT cat.ID, cat.TITLE, cat.CAT, cat.DATE
FROM cat
WHERE cat.ID In (
   SELECT TOP 2 id 
   FROM cat c
   WHERE cat.cat = c.cat  
   ORDER BY [date] DESC,id)
ORDER BY cat.CAT, cat.DATE;
Fionnuala
  • 90,370
  • 7
  • 114
  • 152
  • @Thanks for the vote. I did rollback because an interesting quirk of Access is that you can use a reserved word without square brackets as long as you prefix it with a table or alias. It is a point I am trying to get across in a small way in a post here and there :) – Fionnuala Apr 11 '12 at 13:55
  • Works exactly as I imagined. Frustrating that I could'nt work it out. Thank you very much! – Jaume Apr 17 '12 at 09:21