LINQ - 3子通过计数选择组

时间:2013-05-04 22:35:24

标签: linq group-by having subquery

SQL:

SELECT i.name, l.city, COUNT( l.city ) AS num
FROM locality l
JOIN event e ON e.ID_locality = l.ID
JOIN program p ON p.ID_event = e.ID
JOIN interpreter i ON i.ID = p.ID_interpreter
WHERE i.name = 'XXXX'
GROUP BY l.city
HAVING COUNT( l.city) = (
SELECT MAX( num ) 
FROM ( SELECT COUNT( city ) AS num
FROM (SELECT l.city FROM locality l
JOIN event e ON e.ID_locality = l.ID
JOIN program p ON p.ID_event = e.id
JOIN interpreter i ON i.ID = p.ID_interpreter
WHERE i.name = 'XXXX'
GROUP BY l.city) tmp ) tmp2)

LINQ:

var q4 = from l in db.locality
         join e in db.event on l.ID equals e.ID_locality
         join p in db.program on e.ID equals p.ID_event
         join i in db.interpreter on p.ID_interpreter equals i.ID
         where i.name == "XXXX"
         group l by l.city into grp

您好, 我在LINQ中选择了这个选项。我在SQL中编写了这个选择,但是我不知道如何通过计数来使用多子选择与组...我想选择解释器“XXXX”最常用的城市以及解释器在那里执行的次数。我还检查了enter link description here,但在我尝试使用时它并没有帮助我。如果有人可以帮助我,我会很高兴。 为了更好的定位:databases tables

1 个答案:

答案 0 :(得分:0)

我不确定,但我希望你这样做。

var query = (from l in db.locality
            join e in db.event on l.ID equals e.ID_locality
            join p in db.program on e.ID equals p.ID_event
            join i in db.interpreter on i.ID equals p.ID_interpreter
            group l by new { i.name, l.city } into g
            where i.name == "XXXX" &&
            g.Count(x => x.city) == (from l in db.locality
                                            join e in db.event on l.ID equals e.ID_locality
                                            join p in db.program on e.ID equals p.ID_event
                                            join i in db.interpreter on i.ID equals p.ID_interpreter
                                            where i.name == "XXXX"                  
                                            group l by l.city into g
                                            select new 
                                            {
                                                cityCount = g.Count(x => x.city)
                                            }).Max()

            select new 
            {
                g.key.name,
                g.key.city,
                maxNum = g.count(x => x.city)
            }).ToList();