用每个值选择k行

时间:2016-09-12 12:47:51

标签: mysql

我的表:

NAME    SURNAME
John    Smith
Jane    Smith
Alice   Smith
James   Bond
James   Cameroon
David   Beckham

我有一个数据库,我希望每个k选择SURNAME行。对于k=1它:

SELECT * FROM people GROUP BY SURNAME;

,输出为:

Alice   Smith
James   Bond
James   Cameroon
David   Beckham

我找不到查询k=2的方法,我会得到(如果有的话)2个史密斯,2个债券,2个喀麦隆等或一般:k史密斯,k债券,k喀麦隆等等。如果有SURNAME人少于k人,则选择所有人。可以在MySQL吗?

3 个答案:

答案 0 :(得分:1)

您可以使用以下查询:

SELECT NAME, SURNAME
FROM (
  SELECT NAME, SURNAME,
         @rn := IF(@s = SURNAME, @rn + 1,
                   IF(@s := SURNAME, 1, 1)) AS rn
  FROM mytable
  CROSS JOIN (SELECT @rn := 0, @s = '') AS vars
  ORDER BY SURNAME) AS t
WHERE t.rn <= 3

以上查询显示了k=3的示例。它将从OP中引用的样本表中选择所有记录。

Demo here

答案 1 :(得分:0)

SELECT Name,Surname,Count(SurName) AS k FROM people 
GROUP BY SURNAME
HAVING k>=2

答案 2 :(得分:-1)

您可以区分surname并使用相同的表格加入,但仅限于k。通过这种方式,您将获得每个surname k

SELECT DISTINCT(`surname`)
    LEFT JOIN (
            SELECT `name` FROM `people` p2 where p2.surname = p1.surname limit 2
        ) x
FROM `people` p1