Implementing RANK OVER SQL Clause in C# LINQ

16,692

If you don't need the exact Rank semantics (i.e. tied ranks). You can use the index available with select projections

var rank = data.GroupBy(d => d.CategoryKey)
               .SelectMany(g => g.OrderByDescending(y => y.Rate * @BAES_RATE)              
                                 .Select((x,i) => new{g.Key, Item=x, Rank=i+1}))

Otherwise you can look at this answer

Share:
16,692
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin about 2 years

    I need to implement the following T-SQL clause ....

    RANK() OVER (PARTITION BY a.CategoryKey ORDER BY (x.Rate * @BASE_RATE ) DESC )as Rank
    

    ...in C# LINQ. So far what I've come up with is something like ....

    var rank = data.GroupBy(d => d.CategoryKey)
                   .Select(group => group.OrderByDescending(g => g.Rate * @BAES_RATE) 
    

    I think this would give me each rank partition ordered by rate * BASE_RATE. But what I actually need is the individual rank of a single row, with this being a subquery within a larger result. So really the full SQL query I'm working from is something like ....

    SELECT 
        a.Rate,
        a.CategoryKey,
        a.ID,
        .
        .
        .
        RANK() OVER (PARTITION BY a.CategoryKey ORDER BY (x.Rate * @BASE_RATE ) DESC )as Rank
    FROM data
    
  • Admin
    Admin over 10 years
    Cool thanks, I figured out the answer but this works too
  • Frank Tzanabetis
    Frank Tzanabetis over 8 years
    @MassStrike Care to share your implementation?