SQL到LINQ。 LEFT OUTER JOIN和GROUP BY在一起

时间:2012-05-31 08:59:49

标签: c# sql-server linq group-by left-join

我有表“客户”和列“ID”,“国家”,“性别”。 我想要的是获得按国家/地区字段分组的客户总数以及同一查询中的男性和女性总数。我在sql查询中完成了它。有用。但无法在LINQ中找到如何实现它。

SELECT  c.country, COUNT(c.id) AS TotalClients, 
ISNULL(max(c2.total),0) AS TotalMales,
COUNT(c.id)-ISNULL(MAX(c2.total),0) AS TotalFemails,

FROM Clients c
LEFT OUTER JOIN(
SELECT country, count(id) AS total FROM Clients 
WHERE sex='male'
GROUP BY country
) c2 
ON c2.country = c.country
GROUP BY c.country
ORDER BY c.country

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

var query = (from c in db.Clients
            let TotalMales = (
            from c2 in db.Clients.Where(a=>a.Sex=='male') where c.Country=c2.Country select c2).Count()
            group c by new {c.Country, TotalMales}
            into g
            select new {
                g.Key.Country,
                TotalClients = g.Count(),
                TotalMales = g.Key.TotalMales,
                TotalFemales = g.Count()-TotalMales
            }).OrderBy(s=>s.Country);

答案 1 :(得分:0)

考虑使用更简单的查询:

SELECT
  c.Country,
  SUM(CASE WHEN c.Sex = 'Male' THEN 1 ELSE 0 END) as TotalMales,
  SUM(CASE WHEN c.Sex = 'Female' THEN 1 ELSE 0 END) as TotalFemales,
  COUNT(*) as TotalClients
FROM Clients c
GROUP BY c.Country
ORDER BY c.Country

大致翻译为:

from c in Clients
group c by c.Country into g
order by g.Key
select new {
  Country = g.Key,
  Males = g.Count(y => y.Sex == "Male"),
  Females = g.Count(x => x.Sex == "Female"),
  Total = g.Count()
}