我有一个SQL查询,按多个字段对参与者进行排名.我需要将其转换为LINQ,我知道它没有排名功能.
有人可以帮忙转换吗?
有人可以帮忙转换吗?
如果有帮助,这就是它的作用.此查询从参与者表中提取参与者,并根据列出的字段对它们进行排名RANK()OVER(ORDER BY W desc,L asc,RW asc,RL desc,HP desc,TB desc)AS RANK.接下来,我只抓住那些排名为1或2的地方q1RANK in(‘1′,’2’)并查看这两个排名是否有任何联系有计数(q1.ParticipantID)> 1
@H_502_5@Select q1.RANK,count(q1.ParticipantID) as 'Count' From ( Select Distinct ParticipantID,RANK() OVER (ORDER BY W 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) > 1UPDATE
这是选择所有字段的数据
以下是子查询中过滤数据的示例.从那一组,我看看是否有超过1记录在排名1或排名2.
响应
感谢您的答复到目前为止,我会告诉您什么时候可以尝试这些.
这是另一个问题.改为从控制器调用存储过程会更好吗?这样我就可以保留SQL查询.
我有许多大型查询,我将不得不运行涉及排名.我想知道它是否比重写LINQ中的所有内容更容易.
解决方法
这非常难看,但使用此示例类对我有用.
@H_502_5@public class Participant
{
public int Id { get; set; }
public int score1 { get; set; }
public int score2 { get; set; }
public int ExpectedRank { get; set; }
}
在这个集合上:
@H_502_5@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,score2 = 4,ExpectedRank = 3 },new Participant { Id = 5,new Participant { Id = 6,score2 = 7,ExpectedRank = 2 },};通过执行以下相当丑陋的LINQ查询:
@H_502_5@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);其中产生以下输出:
@H_502_5@{ 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,ExpectedRank = 4 } { Id = 1,Rank = 6,ExpectedRank = 6 }