基于列条目类型对值进行排名

时间:2017-10-25 16:21:35

标签: java sql sqlite

我有一个SQL查询,它对名为' Total'的列进行排名。并将结果返回到名为' Rank'的计算列中。查询如下:

String sql ="select s1.Name as 'NAME',s1.Lang as 'LANGUAGE',"
            + "s1.Total as 'TOTAL',COUNT(DISTINCT s2.Total) AS Rank from Type1 s1 JOIN Type1 s2 on(s1.Total<=s2.Total) GROUP BY s1.ID order by s1.Name ASC ";  

    pst=conn.prepareStatement(sql);
    rs=pst.executeQuery();
    table_statistics1.setModel(DbUtils.resultSetToTableModel(rs));

,结果如下:

| NAME  | LANGUAGE | TOTAL | RANK| 
------------------------------------------------------
| james|French  |70.0|2nd | 
| jimmy|English |90  |1st |
|  josh|French  |60  |3rd |
|  john|English |40  |4th |

我想编写一个查询,它将对总列进行排名,但仅基于语言类型..因为我有两种类型的语言,它将对总列和仅返回法语条目和单独排名的值进行排名仅限英文参赛作品.. 所以输出如下所示:

| NAME  | LANGUAGE | TOTAL | RANK| 
------------------------------------------------------ 
| james |French   |70.0    |1st | 
| jimmy |English  |90      |1st |
|josh   |French   |60      |2nd |
|john   |English  |40      |2nd |
所有的建议都会非常感激。谢谢。

2 个答案:

答案 0 :(得分:1)

排名的常规方法是使用ANSI标准窗口函数:

select t.Name, t.Lang as LANGUAGE, t.Total,
       dense_rank() over (Partition by t.lang order by t.total) as rnk
from Type t;

在SQLite中,你可以这样做:

select t.*,
       (select count(distinct t2.total)
        from t t2
        where t2.lang = t.lang and t2.total <= t.total
       ) as rnk
from Type t;

答案 1 :(得分:1)

谢谢Gordon ..你对dense_rank()替代品的查询没有成功,但是我采取了一个很重要的部分,我的遗失了t2.lang=t.lang 最终的工作代码是:

SELECT S1.*,COUNT(DISTINCT s2.Total) AS Rank from Type s1 JOIN Type s2 on(s2.lang=s1.lang and s1.Total<=s2.Total)GROUP BY s1.ID order by s1.Name ASC

非常感谢老板。