从两个数据表中选择Linq to SQL中的distinct和date difference
本文关键字:中的 SQL to distinct difference date Linq 选择 两个 数据表 | 更新日期: 2023-09-27 18:23:56
我已经尝试了下面的linq到sql查询
DataTable StudentTable=StudentTimeReport.Tables[0];
DataTable RoundEndDateTable=RoundEndDates.Tables[0];
var studentData = from student in StudentTable.AsEnumerable()
join Rounds in RoundEndDateTable.AsEnumerable() on student.Field<string>("strActivityName") equals Rounds.Field<string>("strActivityName")
select student;
两个数据表如下
RoundEndDateTable
ActionName End Date
SQLs 8/31/2014 0:00
Gas Lekage 9/18/2014 0:00
Test Activity 9/20/2014 0:00
学生表
ActionName Player ID Completed Date
Gas Lekage 810045 9/16/2014 14:38
Test Activity 810015 9/16/2014 14:39
我需要得到玩家的日期差异,动作如下
Player ID Action Name Date difference
810015 Gas leakage 2
810015 Test Activity 4
我不确定如何使用Linq到SQL获得具有日期差异的上表。
如果我正确理解你的问题,你希望两个表由ActionName
映射,并且你希望找到每个玩家的CompletedDate
和Date
之间的天数差异。
SELECT PlayerID, ActionName, MAX(DATEDIFF(DAY, Table1.Date, Table2.CompletedDate)) AS DateDifference
FROM Table1
INNER JOIN Table2 ON Table1.ActionName = Table2.ActionName
GROUP BY PlayerID, ActionName
正如你所注意到的,为了确保每个球员都有一个结果,我取最大差值。不管你是否需要,这当然是你的决定,但考虑到你问题的标题,我认为你做到了。
我们可以使用datediff函数
select B.ActionName,
B.PlayerId,
DATEDIFF(day, A.Date, B.completedDate) as difference
FROM B
INNER JOIN A
ON B.ActionName = A.ActionName
var studentData = from redt in RoundEndDateTable
join st in StudentTable on redt.ActionName equals st.ActionName
select new
{
st.PlayerId,
st.ActionName,
((DateTime)st.Completed - (DateTime)redt.Date).TotalDays
}.ToList();
请检查一下。
我得到了下面的代码为我的工作
var studentData = (from redt in RoundEndDateTable.AsEnumerable()
join st in StudentTable.AsEnumerable()
on redt.Field<string>("strActivityName")
equals st.Field<string>("strActivityName")
select new
{
actionName = st.ItemArray[0],
associateId = st.ItemArray[1],
completedDate = st.ItemArray[2],
EndDate = redt.ItemArray[1],
DateDifference = DateTime.Parse(redt.ItemArray[1].ToString()) -
DateTime.Parse(st.ItemArray[2].ToString())
});
从Mukund顽皮地被盗并(希望)修复:
var studentData = (from redt in RoundEndDateTable.AsEnumerable()
join st in StudentTable.AsEnumerable() on redt["ActionName"] equals st["ActionName"]
select new
{
PlayerId = (int)st["PlayerId"],
ActionName = (string)st["ActionName"],
Completed = (DateTime)st["Completed"],
Date = (DateTime)redt["Date"]
})
.Select(sd => new {
sd.PlayerId,
sd.ActionName,
(sd.Completed - sd.Date).TotalDays
})
.ToList();
如果得到InvalidCastExceptions
,请检查数据类型是否匹配。也许您需要实际解析这些值。