使用交叉连接的SQL到Linq转换

时间:2011-01-17 17:00:35

标签: sql linq join cross-join

有人可以帮助将以下sql转换为c#中的linq吗?

select s.SYSTEM_NAME,
       r.RESET_CODE,
       COUNT(v.reset_code) 
  from (select distinct system_name 
          from tbl) s 
cross join (select distinct reset_code 
              from tbl) r 
left join tbl v on v.SYSTEM_NAME = s.SYSTEM_NAME 
               and v.RESET_CODE=r.RESET_CODE 
 group by s.SYSTEM_NAME,r.RESET_CODE 

1 个答案:

答案 0 :(得分:2)

交叉连接通常表示为查询表达式中的子句的多个,或者是扩展方法语法中对SelectMany的调用。

因此查询的第一部分可能是:

var query = from systemName in db.Table.Select(x => x.SystemName).Distinct()
            from resetCode in db.Table.Select(x => x.ResetCode).Distinct()
            ...

左外连接通常用“join ... into ...”查询表示,可能是这样的:

var query = from systemName in db.Table.Select(x => x.SystemName).Distinct()
            from resetCode in db.Table.Select(x => x.ResetCode).Distinct()
            join tmp in db.Table on 
                new { ResetCode = resetCode, SystemName = systemName } 
                equals new { tmp.ResetCode, tmp.SystemName }
                into tmpGroup
            select new { ResetCode = resetCode,
                         SystemName = systemName,
                         Count = tmpGroup.Count() };

我不确定Count部分,说实话......我不是100%确定COUNT(v.ResetCode)在原始SQL中的作用。