使用linq查询在日期时间字段之间选择具有特定时间跨度的记录
本文关键字:时间跨度 记录 选择 之间 查询 linq 日期 字段 时间 使用 | 更新日期: 2024-10-23 16:50:40
我有一个表,其中包含一些关于我的用户及其登录日期时间的记录因此该表具有userId和loginDateTime以及其他必需列。该表按userId分组。
我想为每个组(实际上是每个用户)选择在特定时间跨度(例如2小时)内出现的登录。
为了更好地说明,查询必须在定义的时间窗格中返回有关特定用户的登录信息
例如,该表为:
id userId loginDateTime
----- --------- -----------------------
1 233 01/01/2015 1:04:22 PM
2 233 01/01/2015 2:01:43 PM
3 234 01/01/2015 1:04:12 PM
4 235 01/01/2015 8:22:54 PM
5 235 01/01/2015 1:51:53 PM
6 234 01/01/2015 12:07:32 PM
7 233 01/01/2015 1:09:18 PM
8 233 01/01/2015 4:14:02 PM
用户"233"answers"1小时时间跨度"的结果必须与类似
id userId loginDateTime
----- --------- ------------------------
1 233 01/01/2015 1:04:22 PM
2 233 01/01/2015 2:01:43 PM
7 233 01/01/2015 1:09:18 PM
我正在寻找SQL和等效的LINQ语句。
试试这个:
DECLARE @userId AS INT
DECLARE @timestamnp AS INT
SET @userId = 233
SET @timestamp = -1 --one hour ago from now
SELECT id, userId, loginDateTime FROM myTable
WHERE @userId=233 AND loginDateTime>= DATEADD(hh, @timestamp, GETDATE())
有关DATEADD 的更多信息
我的linq不是很好,但你可以从这样的东西开始。您也可以尝试使用匿名方法进行选择:
DataTable table = new DataTable("Logins");
table.Columns.Add("id", typeof(int));
table.Columns.Add("userId", typeof(int));
table.Columns.Add("loginDateTime", typeof(DateTime));
table.Rows.Add(1, 233, new DateTime(2015, 01, 01, 1, 04, 22));
table.Rows.Add(2, 233, new DateTime(2015, 01, 01, 2, 01, 43));
table.Rows.Add(3, 234, new DateTime(2015, 01, 01, 1, 04, 12));
table.Rows.Add(4, 235, new DateTime(2015, 01, 01, 8, 22, 54));
IEnumerable<DataRow> linkQuery = from times
in table.AsEnumerable()
select times;
List<DataRow> listOfTimes = new List<DataRow>();
DateTime checkAgainst = linkQuery.ElementAt(1).Field<DateTime>("loginDateTime");
foreach (DataRow row in linkQuery)
{
TimeSpan span = new TimeSpan();
DateTime checkedRow = row.Field<DateTime>("loginDateTime");
span = checkAgainst - checkedRow;
if (span.Hours == 0 && span.Minutes <= 59)
{
listOfTimes.Add(row);
}
}
Console.ReadKey();
此外,您可能需要修改时间跨度检查,使其更加精确。