LINQ - LEFT OUTER JOIN with parameter

时间:2014-03-24 16:06:24

标签: linq join parameters

有人可以帮我一个我无法理解的SQL。在T-SQL中,它看起来像这样:

SELECT  v.errandtype
,   COUNT(s.IVRTaskType)
FROM    V_ERRANDS  v
LEFT OUTER JOIN StatisticsRequest s
    ON  s.IVRTaskType = V.IVRTaskType
    AND s.RegistrationDate >= '2014-03-24 00:00:00.000'
    AND s.RegistrationDate <= '2014-03-24 23:59:59.000'
    AND s.CountryID = 0
GROUP BY v.errandtype

但是在LINQ ......这种语言......如此怪异,我只是不明白。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

在linq中,您的请求将如下所示:

var statisticsRequest = yourContext.StatisticsRequest.Where(s =>
    s.RegistrationDate >= new DateTime(2014,03,24) &&
    s.RegistrationDate <= new DateTime(2014,03,25) &&
    s.CountryID == 0);

var results =
    from v in yourContext.V_ERRANDS
    group v by v.errandtype into g
    join s in statisticsRequest on s.IVRTaskType = g.FirstOrDefault().IVRTaskType
    select new {
        s.IVRTaskType,
        g.Count()
    }

答案 1 :(得分:0)

    左侧加入
  • DefaultIfEmpty
  • linq查询之外的
  • DateTime变量
  • 分组的匿名类型,因此您可以计算其他表格列

DateTime start = new DateTime(2014,03,24);
DateTime end = new DateTime(2014,03,25);

var query = from v in context.V_ERRANDS
            from s in context.StatisticsRequest.Where(x => x.IVRTaskType == v.IVRTaskType)
                                               .Where(x => x.RegistrationDate >= start &&  x.RegistrationDate < end)
                                               .Where(x => x.CountryID == 0)
                                               .DefaultIfEmpty()
            group new { v, s} by v.errandtype into g
            select new
            {
              errandtype = g.Key,
              count = g.Select(x => x.s.IVRTaskType).Count(),
            };