我用多个JOIN(包括一个LEFT JOIN)编写了这个SQL请求。 它给了我预期的结果 。
JOIN
LEFT JOIN
SELECT DISTINCT c.Id, c.Title, COUNT(v.Id) AS 'Nb_V2', COUNT(DISTINCT v.IdUser) AS 'Nb_V1', r.cnt AS 'Nb_R' FROM TABLE_C c JOIN TABLE_V v on c.Id = v.Id LEFT JOIN ( SELECT Id, COUNT(*) AS cnt FROM TABLE_R GROUP BY Id ) r ON c.Id = r.Id WHERE c.IdUser = '1234' GROUP BY c.Id, c.Title, r.cnt
但是,“ Id就像此请求的Linq等效项一样,将其放在应用程序的数据访问层中。
我尝试了类似的东西:
var qResult = from c in dbContext.TABLE_C join v in dbContext.TABLE_V on c.IdC equals v.IdC join r in dbContext.TABLE_R on v.IdC equals r.IdC into temp from x in temp.DefaultIfEmpty() group x by new { c.IdC, c.Title /*miss something ?*/} into grouped select new { IdC = grouped.Key.IdC, --good result Title = grouped.Key.Title, --good result NbR = grouped.Distinct().Count(t => t.IdC > 0), --good, but "t.Id > 0" seems weird Count = --I'm lost. No idea how to get my COUNT(...) properties (Nb_V1 and Nb_V2) };
我试图适应这个问题,但我无法弄清楚。我Count对分组子请求的内部迷失了。 谁能解释我哪里错了?
Count
专家提示:如果有人可以用lambda表达式编写等效项,则可获赠积分
要将SQL转换为LINQ查询理解:
DISTINCT
TOP
MIN
MAX
new {
}``groupby
First().field
groupby
JOIN``AND
equals
AND
where
from
Where
DefaultIfEmpty()
into
.DefaultIfEmpty()
COALESCE
?:
null
IN
.Contains()
NOT IN
!
Contains()
BETWEEN
<=
&&
CASE
ISNULL
IIF
SELECT *
SELECT
select new {
}
let
FULL OUTER JOIN
UNION
Concat``DISTINCT``Union``DISTINCT
GROUP BY
GroupBy
.GroupBy(r => 1)
Select
EF.Functions``DbFunctions``EntityFunctions``DbFunctions
LIKE
EF.Functions.Like(column, pattern)
DbFunctions.Like(column, pattern)
将这些规则应用于SQL查询,您将获得:
var subrq = from r in Table_R group r by r.Id into rg select new { Id = rg.Key, cnt = rg.Count() }; var ansq = (from c in Table_C join v in Table_V on c.Id equals v.Id join r in subrq on c.Id equals r.Id into rj from r in rj.DefaultIfEmpty() where c.IdUser == "1234" group new { c, v, r } by new { c.Id, c.Title, r.cnt } into cvrg select new { cvrg.Key.Title, Nb_V2 = cvrg.Count(), Nb_V1 = cvrg.Select(cvr => cvr.v.IdUser).Distinct().Count(), Nb_R = (int?)cvrg.Key.cnt }).Distinct();
lambda转换很棘手,但是需要LEFT JOIN将GroupJoin…转换为… SelectMany:
GroupJoin
SelectMany
var subr2 = Table_R.GroupBy(r => r.Id).Select(rg => new { Id = rg.Key, cnt = rg.Count() }); var ans2 = Table_C.Where(c => c.IdUser == "1234") .Join(Table_V, c => c.Id, v => v.Id, (c, v) => new { c, v }) .GroupJoin(subr, cv => cv.c.Id, r => r.Id, (cv, rj) => new { cv.c, cv.v, rj }) .SelectMany(cvrj => cvrj.rj.DefaultIfEmpty(), (cvrj, r) => new { cvrj.c, cvrj.v, r }) .GroupBy(cvr => new { cvr.c.Id, cvr.c.Title, cvr.r.cnt }) .Select(cvrg => new { cvrg.Key.Title, Nb_V2 = cvrg.Count(), Nb_V1 = cvrg.Select(cvr => cvr.v.IdUser).Distinct().Count(), Nb_R = (int?)cvrg.Key.cnt });