Linq中的SQL查询具有HAVING SUM

时间:2013-12-01 23:03:41

标签: linq-to-sql syntax

我有一个包含三个表的小型数据库示例:Cities,Country和Geo_Languages(各国使用的语言)。现在,我想获得世界上所有城市中口语最多的语言,人口至少有一百万人。

这是SQL-Query:

SELECT SUM(c.population) AS totalPop, g.name_en
FROM cities c,  country cy,  geo_languages g
WHERE   c.country_code = cy.id AND 
    cy.id = g.code2l
GROUP BY g.name_en
HAVING SUM(c.population) > 1000000
ORDER BY totalPop DESC;

到目前为止Linq-Query:

Var query =
    from c in db.City
    join country in db.Country on c.country_code equals country.id
    join languages in db.geo_languages on country.id equals
        languages.code2l    
    group languages by languages.name_en    
    select new{
        totalPop = c.Sum (c => c.population)    
    };

我只是不知道如何将HAVING SUM和ORDER BY转换为Linq。 我很感谢你的帮助。

1 个答案:

答案 0 :(得分:1)

尝试一下:

var query =
    from c in db.City
    join country in db.Country on c.country_code equals country.id
    join languages in db.geo_languages on country.id equals
        languages.code2l    
    group c by languages.name_en into g
    where g.Sum(x => x.population) > 1000000
    select new {
        totalPop = g.Sum(x => x.population)    
    };