0

我想将一列的最多 3 个结果插入 3 个不同的列。

SELECT
    t.name,
    m.top_marks 
FROM
    table_name t,
    (SELECT
         marks
     FROM table_name
     WHERE rownum <=3
     ORDER BY marks DESC) m
GROUP BY column_name DESC;

这可以帮助我获得前三名吗?但是如果我想将前 3 个结果存储在 3 个新列中怎么办?标记1,标记2,标记3?

4

2 回答 2

0

我不能说我真的明白你想要什么......但听起来你可能想要 LIMIT 运算符。看到这个:

SQL - 只选择前 10 行?

所以也许是这样的?

SELECT
    t.name,
    m.top_marks 
FROM
    table_name t,
    (SELECT
         marks
     FROM table_name
     ORDER BY marks DESC
     LIMIT 3) m
GROUP BY column_name DESC;
于 2013-08-21T15:24:13.767 回答
0

您可以使用group_concat()/substring_index()方法执行此操作:

SELECT t.name,
       substring_index(m.marks, ',', 1) as Mark1,
       substring_index(substring_index(m.marks, ',', 2), ',', -1) as Mark2,
       substring_index(substring_index(m.marks, ',', 3), ',', -1) as Mark3
    m.top_marks 
FROM table_name t cross join
     (SELECT group_concat(marks order by marks desc) as marks
      FROM table_name
     ) m
GROUP BY column_name DESC;

如果将它们放在一列中并用逗号分隔值就足够了:

SELECT t.name, substring_index(m.marks, ',', 3) as Marks3
FROM table_name t cross join
     (SELECT group_concat(marks order by marks desc) as marks
      FROM table_name
     ) m
GROUP BY column_name DESC;
于 2013-08-21T15:38:43.613 回答