Linq查询帮助

Linq查询帮助,linq,linq-to-sql,subsonic,linq-query-syntax,Linq,Linq To Sql,Subsonic,Linq Query Syntax,我正试图编写一个linq查询,它使用了几个相关数据表,但遇到了问题 预期结果是:我需要按人口下降率返回每个地区人口最多的三个大都市区 表w/样本数据: MetroAreas--ID、名称 2、大纽约 城市——ID、名称、州ID 1293912,纽约市,10 城市人口——ID、城市ID、普查年份、人口 20212939121008123456789 2112939112007,123454321 MetroAreaCities--ID、CityID、MetroAreaID 119293912,2

我正试图编写一个linq查询,它使用了几个相关数据表,但遇到了问题

预期结果是:我需要按人口下降率返回每个地区人口最多的三个大都市区

表w/样本数据:

MetroAreas--ID、名称
2、大纽约

城市——ID、名称、州ID
1293912,纽约市,10

城市人口——ID、城市ID、普查年份、人口
20212939121008123456789
2112939112007,123454321

MetroAreaCities--ID、CityID、MetroAreaID
119293912,2

说明——ID、名称、地区ID
2006年5月10日,纽约

区域--ID、名称
东北5号

我从地铁区域开始。加入Metroreacities获取城市ID。加入城市以获得州ID。连接状态以获取区域ID。连接区域以便我可以使用where进行筛选。当我试图将城市人口包括在内时,我陷入了困境。我只想要给定区域的三个人口最多的地铁区域。对城市人口进行简单的连接每年都会返回一个记录

(以下是我到目前为止得到的信息,这个查询是为亚音速3编写的):


谁能帮我回答这个问题,或者给我指出正确的方向?非常感谢。

我还没有编译它,但这应该可以让您接近:

var regionID = 5;

var year = (from c in GeoCityPopulation.All()
            select c.CensusYear
           ).Max();

var metros =
    // States in Region
    from s in GeoStateAll()
    where s.RegionID == regionID
    // Cities in State
    join c in GeoCity.All() on s.CityID equals c.ID
    // Metro Area for City
    join mc in GeoMetroAreaCity.All() on c.ID equals mc.CityID
    // Population for City
    join cp in GeoCityPopulation.All() on c.ID equals cp.CityID
    where cp.CensusYear = year
    // Group the population values by Metro Area
    group cp.Population by mc.MetroAreaID into g
    select new
    {
        MetroID = g.Key,      // Key = mc.MetroAreaID
        Population = g.Sum()  // g = seq. of Population values
    } into mg
    // Metro for MetroID
    join m in GeoMetroArea.All() on mg.MetroID equals m.ID
    select new { m.Name, mg.Population };

您希望人口使用哪一年?最近的?平均水平?我想最近一年…精彩!!!只做了很小的改动。。。荣誉我正在认真地跟林克攀谈,不要假装完全理解你所做的一切。你有没有可能告诉我如何修改where cp.CensusYear==year行,只提取CityPopulation表中存在的最大/最大年份?我添加了一个查询来获取最大的CensusYear。如前所述,该查询将单独执行;如果亚音速LINQ提供程序足够聪明,您可以完全删除“year”变量,并将该查询内联,以避免再次访问数据库。
var regionID = 5;

var year = (from c in GeoCityPopulation.All()
            select c.CensusYear
           ).Max();

var metros =
    // States in Region
    from s in GeoStateAll()
    where s.RegionID == regionID
    // Cities in State
    join c in GeoCity.All() on s.CityID equals c.ID
    // Metro Area for City
    join mc in GeoMetroAreaCity.All() on c.ID equals mc.CityID
    // Population for City
    join cp in GeoCityPopulation.All() on c.ID equals cp.CityID
    where cp.CensusYear = year
    // Group the population values by Metro Area
    group cp.Population by mc.MetroAreaID into g
    select new
    {
        MetroID = g.Key,      // Key = mc.MetroAreaID
        Population = g.Sum()  // g = seq. of Population values
    } into mg
    // Metro for MetroID
    join m in GeoMetroArea.All() on mg.MetroID equals m.ID
    select new { m.Name, mg.Population };