簡體   English   中英

每組獲得N個MYSQL

[英]Get N per group MYSQL

問題不在於在GROUP BY中使用LIMIT獲得每個組N個結果?

但我承認這是相似的。

我需要選擇每人前2行。 行按收到年份排序

問題:同一個月可能輸入了2個數據(輸入的日期為YYYY-MM)

我附帶的查詢(在提到的問題之后)被卡在BIG循環中。

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;

樣本數據 :

  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

應出口:

  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

我確信可以用一種更短的方法來完成此操作,但是現在我無法一生解決它的問題。 但這確實有效 -假設您有一個主鍵(應有)並且它稱為id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM