I have messages table: Messages:
Id, Content, Category, createdAt
1, test1, cat1, 2018-03-26 18:22:39
2, test2, cat1, 2018-03-26 18:22:46
3, test3, cat2, 2018-03-26 18:22:52
4, test4, cat2, 2018-03-26 18:23:11
5, test5, cat2, 2018-03-26 18:23:13
6, test6, cat1, 2018-03-26 18:23:17
From this data, I want to select 2 rows of each category i.e. Cat1 & Cat2 with 2 rows each.
So what will be the SQL query to retrieve this data? This is sample data and like this, I have thousands of rows and 20 to 25 different categories. So I want to retrieve the same number of rows from each category. Also, this rows should be in ascending order according to a createdAt column.
Expected Output(Assuming createdAt is latest of bottom rows):
Id, Content, Category, createdAt
6, test6, cat1, 2018-03-26 18:23:17
2, test2, cat1, 2018-03-26 18:22:46
5, test5, cat2, 2018-03-26 18:23:13
4, test4, cat2, 2018-03-26 18:23:11