【问题标题】:LINQ version of sql query with multiple joins and group by具有多个连接和分组依据的 LINQ 版本的 sql 查询
【发布时间】:2023-03-10 03:02:01
【问题描述】:

我有一个 SQL 查询,我正试图将其重写为 LINQ。我已经完成了它的左连接方面,但我无法将它与 group by stuff 结合在一起。

以下是完美运行的 SQL 查询:

select count(c.ID) as NoteCount, count(s.StatusHistoryID) as ActionCount, p.DayGoal
from Collector_Profile p 
left join StatusHistory s on s.AppUserID = p.AppUserID 
and CONVERT(varchar(10), s.StatusDateTZ, 101) = convert(varchar(10), GETDATE(), 101)
left join Claim_Notes c on c.CollectorID = p.ID 
and CONVERT(varchar(10),c.PostDateTZ,101) = convert(varchar(10), GETDATE(), 101)
where p.ID = 1338
group by p.DayGoal

到目前为止,我对 LINQ 查询的了解如下:

var query = from p in _context.Collector_Profile 
    join s in _context.StatusHistory on p.AppUserID equals s.AppUserID into gs
    join c in _context.Claim_Notes on p.ID equals c.CollectorID into gc
    from s in gs.DefaultIfEmpty()
    from c in gc.DefaultIfEmpty()
    where p.ID == CollectorID
    group p by p.DayGoal into grouped

但我不知道如何处理以这种方式截断日期的日期比较,也不知道如何从查询中选择返回的结果。有人能解释一下如何完成这个吗?

【问题讨论】:

  • 您是否只是想按年月日比较日期而忽略小时、分钟等?
  • 是的,但我还需要帮助您了解如何从分组中实际选择结果

标签: c# sql sql-server linq


【解决方案1】:

您可以使用DbFunctions.TruncateTime 方法仅比较日期部分。

DbFunctions.TruncateTime(s.StatusDateTZ)

【讨论】:

  • 那两张表的groupby部分呢,我不知道该怎么做。
  • 我收到错误 DBFunctions 不包含 TruncateTime 的定义。
猜你喜欢
  • 2012-03-24
  • 1970-01-01
  • 2019-02-18
  • 1970-01-01
  • 2011-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多