如何在 linq to sql 中按月计算值?

How do I get a count of values by month in linq to sql?

我有一个 table 的反馈分数,它主要包含一个日期字段和一个 "score" 字段(可能是 "happy"、"neutral" 或 "sad").

我想要 return 一个查询,它按月给出每个分数的计数,如下所示:

但是,我的查询没有正确分组 - 我基本上每个月得到三行(一行用于 "happy",一行用于 "neutral",另一行用于 "sad" ,像这样:

如何将数据聚合在一起?

我现在的查询是这样的:

var monthlyScore = from f in db.tl_feedbacks
    group f by new { month = f.timestamp.Month, year = f.timestamp.Year, score = f.tl_feedback_score.score } into g
     select new
            {
              dt = string.Format("{0}/{1}", g.Key.month, g.Key.year),
              happyCount = g.Where(x => x.tl_feedback_score.score == "happy").Count(),
              neutralCount = g.Where(x => x.tl_feedback_score.score == "neutral").Count(),
              sadCount = g.Where(x => x.tl_feedback_score.score == "sad").Count(),
              total = g.Count()

          };

从您的分组中删除 , score = f.tl_feedback_score.score