SQL Query in Linq with HAVING SUM

≡放荡痞女 提交于 2020-01-06 13:04:27

问题


I have a small database example with three tables: Cities, Country and Geo_Languages (Languages spoken in the countries). Now I want to get the most spoken languages of all cities in the world with a population of at least one million people.

Here is the 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;

Here the Linq-Query so far:

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)    
    };

I just don't know how to convert the HAVING SUM and the ORDER BY into Linq. I'm thankful for any help.


回答1:


Try that one:

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)    
    };


来源:https://stackoverflow.com/questions/20318380/sql-query-in-linq-with-having-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!