繁体   English   中英

在Linq中使用SQL Server的Row_Number

[英]Using Row_Number of SQL Server in Linq

我有一个数据表

Date         Users
------------------
01/03/2015    25
02/03/2015    28
04/03/2015    36
07/03/2015    45
08/03/2015    47

我已经使用Row_Number在Sql Server中创建了一个表值函数,该函数给了我类似下面的输出,用于进一步处理

Date         Users      UsersAdded
----------------------------------
01/03/2015    25        0
02/03/2015    28        3
04/03/2015    36        8
07/03/2015    45        9
08/03/2015    47        2

但是,我现在需要在Linq中做同样的事情,但是它没有Row_Number函数。 我看看如何将使用ROW_NUMBER()的查询转换为linq? 但这与我的查询无关。

我在SQL查询中在日期字段上有Rownum,查询是

select date, Users, (T1.Users - isnull(T2.Users,0)) as UsersAdded
from tableuser T1 
join tableuser T2 on T1.Rownum = (T2.RowNum +1)

我是LINQ的新手,所以甚至不知道如何开始此查询。 任何帮助,将不胜感激。

使用日期栏里找到董下一最低日期使用左外连接from / where

var ans = from t1 in tableuser from t2 in tableuser.Where(t2 => t2.Date == tableuser.Where(t3 => t3.Date < t1.Date).Max(t3 => t3?.Date)).DefaultIfEmpty()
          select new { t1.Date, t1.Users, UsersAdded = t1.Users - (t2?.Users ?? t1.Users)};

PS我认为您的示例查询可能与第一个答案行有问题?

使用LINQ进行反对。 请参阅链接https://msdn.microsoft.com/en-us/library/bb534869.aspx

这样会实现

 string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" }; var query = fruits.Select((fruit, index) => new { index, str = fruit.Substring(0, index) }); foreach (var obj in query) { Console.WriteLine("{0}", obj); } /* This code produces the following output: {index=0, str=} {index=1, str=b} {index=2, str=ma} {index=3, str=ora} {index=4, str=pass} {index=5, str=grape} */ 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM