c# - LINQ to Entities 中的 SQL 排名

标签 c# linq

我有一个 SQL 查询,可以按多个字段对参与者进行排名。我需要将其转换为 LINQ,据我所知,它没有排名功能。 有人可以帮忙转换吗?

如果有帮助,下面就是它的作用。此查询从排名表中提取参与者并根据列出的字段对他们进行排名 RANK() OVER (ORDER BY W desc, L asc, RW asc, RL desc, HP desc, TB desc) AS RANK .接下来我只抓取排名 1 或 2 的那些 Where q1.RANK in ('1','2')看看这两个排名是否有联系 Having count(q1.ParticipantID) > 1

Select q1.RANK, count(q1.ParticipantID) as 'Count'
From (
        Select Distinct ParticipantID, RANK() OVER (ORDER BY W desc, L asc, RW asc, RL desc, HP desc, TB desc) AS RANK
        From vGroupStandings
        Where CompetitionID = 8
        and GroupNumber = 1
        and EventID = 6
     ) as q1
Where q1.RANK in ('1','2')
Group By q1.RANK
Having count(q1.ParticipantID) > 1

更新

这里是选择所有字段的数据

enter image description here

下面是子查询中过滤数据的示例。从该集合中,我查看是否有超过 1 条记录排在第 1 位或第 2 位。

enter image description here

响应

感谢您到目前为止的回复,我会在可以试用时通知您。 这是另一个问题。从 Controller 调用存储过程会更好吗?这样我就可以保留 SQL 查询。 我将不得不运行许多涉及排名的大型查询。我想知道这是否比在 LINQ 中重写所有内容更容易。

最佳答案

这很丑陋,但使用这个示例类对我有用。

public class Participant
{
    public int Id { get; set; }
    public int Score1 { get; set; }
    public int Score2 { get; set; }
    public int ExpectedRank { get; set; }
}

关于这个集合:

var participants = new Participant[] {
    new Participant { Id = 1, Score1 = 2, Score2 = 5, ExpectedRank = 6 },
    new Participant { Id = 2, Score1 = 10, Score2 = 8, ExpectedRank = 1 },
    new Participant { Id = 3, Score1 = 7, Score2 = 2, ExpectedRank = 4 },
    new Participant { Id = 4, Score1 = 7, Score2 = 4, ExpectedRank = 3 },
    new Participant { Id = 5, Score1 = 7, Score2 = 2, ExpectedRank = 4 },
    new Participant { Id = 6, Score1 = 7, Score2 = 7, ExpectedRank = 2 },
};

通过执行以下相当丑陋的 LINQ 查询:

var ranked = participants
    .OrderByDescending(p => p.Score1)
    .ThenByDescending(p => p.Score2)
    .Select((p, i) => new { Order = 1 + i, Participant = p })
    .GroupBy(p => new { p.Participant.Score1, p.Participant.Score2 })
    .SelectMany(g => g.Select(p => new {
        Id = p.Participant.Id,
        Rank = g.Min(x => x.Order),
        ExpectedRank = p.Participant.ExpectedRank
    }));

foreach (var p in ranked)
    Console.WriteLine(p);

产生以下输出:

{ Id = 2, Rank = 1, ExpectedRank = 1 }
{ Id = 6, Rank = 2, ExpectedRank = 2 }
{ Id = 4, Rank = 3, ExpectedRank = 3 }
{ Id = 3, Rank = 4, ExpectedRank = 4 }
{ Id = 5, Rank = 4, ExpectedRank = 4 }
{ Id = 1, Rank = 6, ExpectedRank = 6 }

关于c# - LINQ to Entities 中的 SQL 排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30060889/

相关文章:

asp.net - Linq 与 Entity Framework 预加载

c# - 在 ulong (C#) 中获得最后一个有效位的最快方法?

c# - IIS 托管 WCF 服务和使用 Windows 身份验证的 SQL 查询

c# - 如何在 Collection<T> 上使用 ToList

linq - 如何计算嵌套集合/代码优先 Entity Framework 中的项目

c# - 解析多个集合并获取单个列表的 LINQ 语句

vb.net - 使用 VB.NET 和 LINQ 的左外连接 null

控制 AutoCAD 相机的 C# 代码

c# - 使用 C# 的线程池问题

c# - 在 WPF Viewbox 中对齐内容