如何在子查询中使用groupby将此tSQL语句转换为LINQ
本文关键字:tSQL 将此 语句 转换 LINQ groupby 查询 | 更新日期: 2023-09-27 17:59:14
我正在尝试将以下MSSQL查询转换为LINQ。我正在使用具有以下语法的实体框架来获取数据。
var rv = (from i in DC.TableA select i).ToList();
这是我想为其编写C#LINQ查询的sql,但我无法理解。有人能帮忙吗?
select BTO.*
from TableA BTO
join
(
select eqnum, max(testdate) as testdate
from TableA BTO1
where
BTO1.eqnum in ('M0435', 'Z0843') and
BTO1.testdate <= '2008-06-01'
group by eqnum
) T1
on
T1.eqnum = BTO.eqnum and
T1.testdate = BTO.testdate
order by EqNum;
我认为有机会重写您的查询,但出于信息目的,我逐字逐句地将您的sql
重写为linq
。
如果您解释您试图实现的目标,我们可以提供替代sql
/linq
var eqnums = new[] { "M0435", "Z0843" };
var testdate = "2008-06-01";
var query = from bto in DC.TableA
join t1 in (
from bto1 in DC.TableA
where eqnums.Contains(bto1.eqnum) &&
bto1.testdate.CompareTo(testdate) <= 0
group bto1 by bto1.eqnum into g
select new
{
eqnum = g.Key,
testdate = g.Max(x => x.testdate)
}
) on new { bto.eqnum, bto.testdate } equals new { t1.eqnum, t1.testdate }
orderby bto.eqnum
select bto;