0

此查询拉回两列,一个是用户 ID 列,一个是当月总销售额的列。

我需要添加一个对它们进行排名的列(它与第 # 行完全相同)

我需要将它从 SQL 转换为 LINQ 或 Lambda。

select pu.userID, SUM(o.OrderTotal) as OrderTotal 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
340 68992.74
318 49575.05
228 42470.88
278 38196.87
291 36220.52
351 34962.32
422 31764.67
178 31433.41
430 30836.77
212 30375.99
4

1 回答 1

1

要使用 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
于 2014-05-23T06:11:58.140 回答