-1

I have a table in which I needed the latest 2 rows from each type of records. using GROUP BY.

For example, from the picture below, what I want is to get last 2 records depending date column from each page type. I know GROUP BY will be used but I am not quite familiar with that.. Thanks

enter image description here

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Syed Saqlain
  • 544
  • 4
  • 21

4 Answers4

1

Long story short, once you have so little different types, you could use an UNION aproach:

SELECT * FROM (SELECT * FROM table WHERE page = 'sometype' ORDER BY date limit 2) t
UNION ALL 
SELECT * FROM (SELECT * FROM table WHERE page = 'someothertype' ORDER BY date limit 2) t
UNION ALL 
SELECT * FROM (SELECT * FROM table WHERE page = 'otherothertype' ORDER BY date limit 2) t
...

Just repeat this for each "page" type you have.

If this solution doesn't fits you, take a look at this article: http://www.sqlines.com/mysql/how-to/get_top_n_each_group

Cheers

Nikao

nicolasl
  • 421
  • 3
  • 16
0

You can use correlated subquery with limit clause :

select t.*
from table t
where id in (select t1.id
             from table t1
             where t1.page = t.page
             order by t1.date desc
             limit 2
            );

However, only GROUP BY would not sufficient to do this you might need JOIN.

Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52
0

you can use row_number window function if your mysql version 8+ but if below then you may use below method of generating row number

set @num := 0, @page:= '';

select x.*
from (
   select t.*,
      @num := if(@page= page, @num + 1, 1) as row_number,
      @page:= page as d
  from table t
  order by date desc
) as x where x.row_number <= 2;
Zaynul Abadin Tuhin
  • 31,407
  • 5
  • 33
  • 63
0

You can't use just GROUP BY to get the result you want. You can only do that with subqueries and GROUP_CONCAT. See this: Using LIMIT within GROUP BY to get N results per group?

If your MySQL version doesn't support these features you will need a different approach:

  1. Get a list of all the different page types: SELECT DISTINCT page;
  2. Programmatically iterate over the list of page types and SELECT ... LIMIT 2; from the main table

You should be aware that these two approaches might have very different performance if you have a huge database.

Yoshimitsu
  • 370
  • 2
  • 9