SQL分数排名自我加入,COUNT

时间:2015-02-25 01:10:16

标签: sql

基于表格得分列得分,写下查询以获得得分和排名。

以下是代码:

    SELECT Scores.Score, Q2.Rank 
        FROM(
            Scores
            LEFT JOIN
            (SELECT DISTINCT Scores.Score AS Dis_score,
COUNT(DISTINCT(Scores.Score) AS Rank FROM Scores)AS Q2 
    ON Scores.Score = Q2.Dis_score)   
        ORDER BY Scores.Score DESC;

Input:  {"headers": {"Scores": ["Id", "Score"]}, "rows": {"Scores": [[1, 0.00], [2, 0.00], [3, 0.01]]}}
Output: {"headers": ["Score", "Rank"], "values": [[0.01, null], [0.00, 2], [0.00, 2]]}
Expected:   {"headers": ["Score", "Rank"], "values": [[0.01, 1], [0.00, 2], [0.00, 2]]}

说到上面的情况,为什么0.01返回COUNT()和null ???

1 个答案:

答案 0 :(得分:0)

我想你想要一个子查询:

SELECT s.*,
       (SELECT COUNT(DISTINCT s2.score)
        FROM scores s2
        WHERE s2.score <= s.score
       ) as rank
FROM Scores s;

您的问题不清楚是否需要<=>=