无法将简单的SQL转换为Linq

时间:2011-07-05 20:14:46

标签: sql linq linq-to-sql

我很难将其转换为LINQ:

SELECT 
 COUNT(1) AS Registrations, 
 YEAR(Join_date) AS Year, 
 MONTH(Join_date) AS Month
FROM tblForumAuthor
GROUP BY YEAR(Join_date), MONTH(Join_date)
ORDER BY Year, Month

这只是一个简单的报告,但我无法弄清楚如何按组进行分组并算作选择新组。我只是做了这个可悲的尝试:

var q = (from c in db.tblForumAuthors 
         select new {Year = c.Join_date.Year, 
                     Month = c.Join_date.Month, 
                     Registrations = });

6 个答案:

答案 0 :(得分:1)

db.tblForumAuthors
.GroupBy(c => new {c.Join_date.Month, c.Join_date.Year})
.OrderBy(g => g.Key.Year).ThenBy(g => g.Key.Month)
.Select(g => new
{
    Registrations = g.Count(),
    Year = g.Key.Year
    Month = g.Key.Month
});

答案 1 :(得分:1)

var results = db.tblForumAuthors.GroupBy(r => new {Year = r.Join_date.Year, Month =  r.Join_date.Month})
                .Select(g => new {Registrations = g.Count(),  g.Key.Year, g.Key.Month})
                .OrderBy(r => r.Year)
                .ThenBy(r => r.Month)

答案 2 :(得分:1)

from c in db.tblForumAuthors 
group c by new {month = t.Join_Date.Month, year = t.Join_Date.Year} 
into g select new {month = g.Key.month, year = g.Key.year, count = g.Count()}

答案 3 :(得分:1)

掏出帖子......但这应该可以解决问题。请注意如何使用匿名类型按多个字段进行分组。组的属性可通过分组的Key属性获得。但不确定这是否会产生Count(1)。 IIRC将是Count(*)

from c in db.tblForumAuthors
group c by new { c.Join_date.Year, c.Join_date.Month } into g
orderby g.Year, g.Month
select new {
    Registrations = g.Count(),
    g.Key.Year,
    g.Key.Month
};  

答案 4 :(得分:1)

我敢打赌有更好的方法可以做到,但这里有一个。

如果表格中有两个字段定义如下:

tblForumAuthor
==========================
Join_Date    date
Name         nvarchar(50)

您可以按照以下方式获取每月加入+年组合的人数报告:

var db = new DataClasses1DataContext();

var report =
    from a in db.tblForumAuthors
    group a by new {Year = a.Join_Date.Year, Month = a.Join_Date.Month}
    into g
    select new
               {
                   Year = g.Key.Year,
                   Month = g.Key.Month,
                   Registrations = g.Count()
               };

foreach( var item in report)
{
    Console.WriteLine(item.Year + " " + item.Month + " " + item.Registrations);
}

答案 5 :(得分:0)

它更像是这样 - 抱歉没有能力进行测试

var results = from r in tblForumAuthorm 
group r by r.Join_date into  
select new { Year =r.Join_Date.Year, Month = r.join_date.month };