【问题标题】:Linq to SQL Left Join, Order and Group By CountLinq to SQL Left Join, Order and Group By Count
【发布时间】:2013-07-30 20:56:59
【问题描述】:

我的这个查询运行良好:

SELECT B.ID, B.NAME, COUNT(BU.ID) AS TOTAL
FROM Building B
LEFT JOIN BuildingUser BU ON BU.ID_BUILDING = B.ID    
GROUP BY B.ID, B.NAME
ORDER BY COUNT(BU.ID) DESC, B.NAME

但是,当我将它转换为 Linq 时,我没有得到预期的结果。当左连接返回 null 时,它返回 count = 1。所以,我一直在尝试这个查询:

var list1 = (from building in db.GetTable<Building>()
             join entitybuildinguser in db.GetTable<BuildingUser>()
                 on building.ID equals entitybuildinguser.ID_BUILDING into tmpbuildinguser
                 from buildinguser in tmpbuildinguser.DefaultIfEmpty()                 
             group building by new
             {
                 building.ID,
                 building.NAME
             } into grpBuilding                                                
             orderby grpBuilding.Select(g => g.ID).Count() descending, grpBuilding.Key.NAME
             select new
             {
                 ID_BUILDING = grpBuilding.Key.ID,
                 NAME = grpBuilding.Key.NAME,
                 users = grpBuilding.Select(g => g.ID).Count()
             });

【问题讨论】:

  • 你的sql正确吗?你只剩下加入用户并且什么都不做。我错过了什么吗?
  • @ErenErsönmez 你是对的。我已经从 INNER 变成了 LEFT,忘记拿出来了。就算出局也不会改变最终结果。
  • 您正在按 ID 对建筑物进行分组,因此该组中只会有一个建筑物(假设 ID 是唯一的)。您的第一个分组是否应该分组 buildingUser 而不是 building

标签: c# sql linq linq-to-sql


【解决方案1】:

试试这个:

from b in db.Buildings
join u in db.BuildingUsers on b.ID equals u.ID_BUILDING into g
orderby g.Count() descending, b.Name descending
select new 
{
    Id = b.ID,
    Name = b.NAME,
    Total = g.Count()
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多