2013-08-21 60 views
0

我想將列的最大3個結果插入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個結果存儲在3個新列中呢? Marks1,marks2,marks3?

+0

[樞軸] (http://stackoverflow.com/questions/7674786/mysql-pivot-table)?我想你可能需要添加像行號字段這樣的工作。 – Dukeling

回答

0

我不能說我真的明白你要做什麼......但聽起來你可能想要LIMIT操作符。看到這一點:

SQL - Select first 10 rows only?

因此,也許這樣的事情?

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; 
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; 
相關問題