如何在子查询中使用group by将此tSQL语句转换为LINQ

时间:2015-06-22 19:17:19

标签: c# sql-server linq tsql

我正在尝试将以下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;

1 个答案:

答案 0 :(得分:2)

我认为有机会重写您的查询,但出于信息目的,我将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;