在mysql中排名

时间:2009-09-17 13:05:35

标签: sql mysql

我读了this article,我在oracle中有代码,但是我希望将它转换为适用于MySQL的代码。在Oracle中,我使用函数rank,有四列可以符合或不符合,如何在mysql中使用它,或者,这是不可能的?

这是代码,我想选择最符合条件的行,每行可以有4列完成,我想排名其中一列有更多数据。

SELECT vlr,
       data
INTO   vn_vlr,
       vd_data
FROM (SELECT a.*, rank() over (ORDER BY nvl(a.id_categoria, -1) DESC,
             nvl(a.id_peso, -1) DESC,
             nvl(a.id_faixa, -1) DESC,
             nvl(a.sexo, ' ') DESC ) rank
        FROM tab_regra_pagamento a
       WHERE a.id_competicao = pidcompedticao
         AND a.tipo = 'NORMAL'
         AND a.data_vencimento > SYSDATE
         AND nvl(a.id_categoria, vid_categoria) = vid_categoria
         AND nvl(a.id_faixa, vid_faixa) = vid_faixa
         AND nvl(a.id_peso, vid_peso) = vid_peso
         AND nvl(a.sexo, vsexo) = vsexo)
WHERE  rank = 1;

1 个答案:

答案 0 :(得分:3)

SELECT  @rank := @rank + (@value <> value),
        @value := value
FROM    (
        SELECT  @rank := 0,
                @value := -1
        ) vars,
        mytable
ORDER BY
        value

在您的情况下,当您只需要第一组值的所有副本时:

SELECT  vlr, data
FROM    tab_regra_pagamento a
WHERE   a.id_competicao = pidcompedticao
        AND a.tipo = 'NORMAL'
        AND a.data_vencimento > SYSDATE
        AND (a.id_cetegoria, a.id_faixa, a.id_peso, a.sexo) =
        (
        SELECT  ai.id_cetegoria, ai.id_faixa, ai.id_peso, ai.sexo
        FROM    tab_regra_pagamento ai
        WHERE   ai.id_competicao = pidcompedticao
                AND ai.tipo = 'NORMAL'
                AND ai.data_vencimento > SYSDATE
        ORDER BY
                a.id_cetegoria DESC, a.id_faixa DESC, a.id_peso DESC, a.sexo DESC
        LIMIT 1
        )