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

时间:2015-03-12 16:41:21

标签: linq linq-to-sql linq-group

我有一个反馈分数表,其中包含一个日期字段和一个"得分"字段(可能是"快乐","中立"或"悲伤")。

我想返回一个查询,它会按月向我提供每个分数的计数,如下所示:

enter image description here

但是,我的查询并没有正确分组 - 我基本上每个月都会获得三行("一行#34;快乐"一个"中性"和#34;悲伤",像这样:

enter image description here

如何将数据汇总在一起?

我现在的询问是:

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()

          };

1 个答案:

答案 0 :(得分:1)

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