SQL Server - 根据列显示行的排名

时间:2018-05-09 10:19:33

标签: sql sql-server tsql sql-server-2014

我有一个返回的查询:

RowNumber     Name
===================================
1             Invoice-02116 (1).pdf
1             Invoice-02116 (2).pdf
1             Invoice-02116.pdf
2             Invoice-02116.pdf
3             Invoice-02116.pdf
4             Invoice-02116.pdf
5             Invoice-02116.pdf

我需要的是:

RowNumber     Name
===================================
1             Invoice-02116 (1).pdf
2             Invoice-02116 (2).pdf
3             Invoice-02116.pdf
3             Invoice-02116.pdf
3             Invoice-02116.pdf
3             Invoice-02116.pdf
3             Invoice-02116.pdf

更确切地说,根据名称列显示排名。

我在RowNumber列中使用的是:

SELECT ROW_NUMBER() OVER (PARTITION BY ff.Name ORDER BY ff.Name) AS RowNumber, ff.Name

2 个答案:

答案 0 :(得分:3)

改为使用DENSE_RANK

SELECT DENSE_RANK() OVER (ORDER BY ff.Name) AS RowNumber... 

答案 1 :(得分:2)

使用DENSE_RANK并使用适当的顺序:

SELECT
    DENSE_RANK() OVER (ORDER BY LEN(Name) DESC, Name) AS RowNumber, 
    Name
FROM yourTable;

Demo