我有一个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
更新
这里是选择所有字段的数据
以下是子查询中过滤数据的示例。从那个集合中,我看看是否有超过1个记录排名在1级或2级。
RESPONSE
感谢您到目前为止的回复,我会告诉您何时可以尝试这些回复。 这是另一个问题。改为从控制器调用存储过程会更好吗?这样我就可以保留SQL查询。 我有许多大型查询,我将不得不运行涉及排名。我想知道它是否比重写LINQ中的所有内容更容易。
答案 0 :(得分:2)
这非常难看,但是对我来说这个样本类很有用。
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 }
答案 1 :(得分:1)
像这样......这是伪代码....我没有测试。
如果您提供了任何示例数据和预期输出,那么我会这样做
var inner = datasource
.OrderByDesc(x => x.W)
.ThenBy(x => x.L)
// etc for all orders you need
.GroupBy(new { W = W, L = L, RW = RW, RL = RL, HP = HP, TB = TB })
.First(2);
if (inner[0].Count > 1 || inner[1].Count[1] > 1)
{
Console.Writeline("1 "+inner[0].Count.ToString());
Console.Writeline("2 "+inner[1].Count.ToString());
}