0

我正在尝试获取给定 GROUP BY 条件的 TOP X 结果。我目前正在使用这样的东西:

SELECT * FROM 
        (SELECT id  
            FROM myTable 
            WHERE id IN (x1, x2, ..., xn) GROUP BY id ORDER BY grade DESC 
        ) t1 
        INNER JOIN myTable t2 ON t2.id=t1.id

id 是一个非唯一的 INT 索引字段,每个值有多个行。

这将为每个 ID 返回我,即成绩最好的行。如何将其转换为返回每个 id 的 TOP X 结果?

例如,对于以下数据

id  grade
2   10
2   13
2   15
3   20
4   16
4   55
4   45
4   35
4   25
5   1

假设 TOP X 中的 X 为 2,我想获得以下行:

id grade  
2  15  
2  13  
3  20  
4  50  
4  40  
5  1  
4

2 回答 2

0

也许,像这样的东西?

SELECT m.*
FROM (
  SELECT id
  FROM myTable 
  WHERE id IN (1, 3)
  GROUP BY id
) AS ids
RIGHT JOIN myTable AS m ON ids.id = m.id
WHERE
  m.id = ids.id AND
  m.grade IN (
    SELECT TOP 5 t.grade
    FROM myTable AS t
    WHERE t.id = ids.id
    ORDER BY t.grade DESC
  );

UPD:或者,甚至

SELECT m.*
FROM myTable AS m
WHERE
  m.id IN (1, 2) AND
  m.grade IN (
    SELECT TOP 5 t.grade
    FROM myTable AS t
    WHERE t.id = m.id
    ORDER BY t.grade DESC
  );
于 2013-11-10T08:49:15.513 回答
0

这取决于您是否希望退回领带。

如果您希望返回关系,可以使用以下方法:

CREATE TABLE grades (
  id INT,
  grade INT
);

INSERT INTO grades VALUES (1, 2);
INSERT INTO grades VALUES (1, 3);
INSERT INTO grades VALUES (1, 4);
INSERT INTO grades VALUES (1, 5);

INSERT INTO grades VALUES (2, 5);
INSERT INTO grades VALUES (2, 5);
INSERT INTO grades VALUES (2, 5);
INSERT INTO grades VALUES (2, 4);

INSERT INTO grades VALUES (3, 3);
INSERT INTO grades VALUES (3, 4);

INSERT INTO grades VALUES (4, 3);

SELECT id, grade
  FROM grades g
WHERE (
   SELECT COUNT(DISTINCT grade) FROM grades
   WHERE id = g.id
      AND grade >= g.grade
) <= 2;

输出:

身份等级
1 4
1 5
2 5
2 5
2 5
2 4
3 3
3 4
4 3

如果您不想要领带,请使用 DISTINCT:

SELECT DISTINCT id, grade
  FROM grades g
WHERE (
   SELECT COUNT(DISTINCT grade) FROM grades
   WHERE id = g.id
      AND grade >= g.grade
) <= 2;

输出:

身份等级
1 4
1 5
2 5
2 4
3 3
3 4
4 3

SQLFiddle:SQLFiddle

于 2013-11-10T08:51:36.783 回答