2011-06-17 50 views
0

C#或VB.NET很好。LINQ to SQL计数表与关系

我想从与LINQ下表计算的人数为每个国家到SQL

我有两个表,一个是国家和其他人是。这是从国家到人民的一对多关系。

Countries table column:CountryId,CountryName 
People:PeopleId,FullName,CountryId (a primary key from Country table and allowed null) 

我想统计每个国家有多少人,并得到如下结果,只显示有人的国家。 因为有些国家在People表中没有人。

  • 美国:10
  • 中国:20
  • 俄罗斯:15

等..

谢谢。

回答

2
(from c in Countries 
select new { c.CountryName, Count = c.People.Count()}).Where(r => r.Count > 0) 

from c in Countries.Where(r => r.People.Any()) 
select new { c.CountryName, Count = c.People.Count()} 
0

那么其一定的技巧..你必须使用LINQ使用的关系,尝试使用此查询

var count = from pl in dc.People join ci in dc.Countries on pl.CountryId equals ci.CountryId groupby ci.CountryId select PeopleId.count(); 

还有很多其他的方式来编写LINQ查询但它是最简单的方法..有关LINQ to SQL的更多信息,可以查看我的博客:LinqtoSQL

+0

Thi s查询不会返回想要的结果,它当然不是最简单的方法 – Vedran 2011-06-17 08:09:20

+0

我测试过了! – casper123 2011-06-17 12:20:59