简体   繁体   中英

Get N per group MYSQL

IT IS NOT THE SAME QUESTION THAN : Using LIMIT within GROUP BY to get N results per group?

but i admit it's similar.

I need to select the first 2 rows per person. the rows are ordered by Year recieved

Problem : there is a possibility than 2 data were entered the same month (Date is entered YYYY-MM)

The query I came with (following the refered question) is stuck in an BIG loop.

SELECT *
FROM `table_data` as b
WHERE (
    SELECT count(*) FROM `table_data` as a
        WHERE a.Nom = b.Nom and a.year < b.year
    ) <= 2;

Sample Data :

  A  |   year   |  Nom
---------------------
  b  |  2011-01 | Tim
---------------------
  d  |  2011-01 | Tim
---------------------
  s  |  2011-01 | Tim
---------------------
  a  |  2011-03 | Luc
---------------------
  g  |  2011-01 | Luc
---------------------
  s  |  2011-01 | Luc

Should export :

  A  |   year   |  Nom
---------------------
  b  |  2011-01 | Tim
---------------------
  d  |  2011-01 | Tim
---------------------
  a  |  2011-03 | Luc
---------------------
  g  |  2011-01 | Luc
(
 -- First get a set of results as if you only wanted the latest entry for each
 -- name - a simple GROUP BY from a derived table with an ORDER BY
  SELECT *
  FROM (
    SELECT *
    FROM `table_data`
    ORDER BY `year` DESC
  ) `a`
  GROUP BY `Nom`
)
UNION
(
 -- Next union it with the set of result you get if you apply the same criteria
 -- and additionally specify that you do not want any of the rows found by the
 -- first operation
  SELECT *
  FROM (
    SELECT *
    FROM `table_data`
    WHERE `id` NOT IN (
      SELECT `id`
      FROM (
        SELECT *
        FROM `table_data`
        ORDER BY `year` DESC
      ) `a`
      GROUP BY `Nom`
    )
    ORDER BY `year` DESC
  ) `b`
  GROUP BY `Nom`
)
 -- Optionally apply ordering to the final results
ORDER BY `Nom` DESC, `year` DESC

I feel sure there is a shorter way of doing it but right now I can't for the life of me work out what it is. That does work , though - assuming you have a primary key (which you should) and that it is called id .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM