要使用 SQL 捕获排名索引,您可以简单地修改当前的 sql,如下所示:
SELECT pu.userid,
SUM(o.OrderTotal) AS OrderTotal,
ROW_NUMBER() OVER (ORDER BY SUM(o.ordertotal) DESC) AS [Rank]
FROM ProPit_User pu
INNER JOIN SeperateDB.dbo.Orders o ON pu.salesrepid = o.salesrepid
AND o.DateCompleted > '2014-05-01' AND o.DateCompleted < '2014-05-23'
GROUP BY pu.userid
ORDER BY SUM(o.OrderTotal) DESC
这将产生
userID OrderTotal Rank
340 68992.74 1
318 49575.05 2
228 42470.88 3
etc
不确定要在哪种情况下“转换为 LINQ”。如果您的意思是在 EF 或 Linq-to-Sql 上下文中针对这两个表进行 linq 查询,那么这些语句将产生与上述相同的结果:
var minDate = new DateTime(2014,5,1);
var maxDate = new DateTime(2014,5,23);
-- the linq to sql query:
-- join on salesrepid, group by userid, sum the ordertotals
var dbQuery = ProPit_Users.GroupJoin(
Orders,
pu => pu.salesrepid,
o => o.salesrepid,
(pu, orders) => new
{
pu.UserId,
OrderTotal = orders.Where(o => o.datecompleted > minDate && o.datecompleted. < maxDate )
.Sum(o => o.ordertotal)
}
)
.OrderByDescending(row => row.OrderTotal)
-- materialize the db query
.ToList();
-- add ranking to the results of the query
var userRankings = dbQuery.Select((row, idx) => new { Rank = ++idx, row.UserId, row.OrderTotal });
这将产生一个对象列表:
Rank UserID OrderTotal
1 340 68992.74
2 318 49575.05
3 228 42470.88
etc