创建日期和平均值的查询

时间:2012-07-09 17:12:01

标签: c# sql linq

我需要从datacontext的表中选择日期和平均值,我需要按年和月分组。 在SQL中它看起来像这样

select Year(data) as years, Month(data) as months, Avg(value) as prices from Prices
group by Year(data),MONTH(data)
order by years, months

我已经创建了一个LINQ查询

var query0 = from c in dc.Prices
             where Convert.ToDateTime(c.data).CompareTo(left) >= 0
                   && Convert.ToDateTime(c.data).CompareTo(right) <= 0
                   && c.idsticker.Equals(x)
              group c by new { ((DateTime)c.data).Year, ((DateTime)c.data).Month }
                    into groupMonthAvg
              select groupMonthAvg;

但我不知道如何获得结果中的平均值

3 个答案:

答案 0 :(得分:1)

只需使用select中的Average功能:

var query0 = from c in dc.Prices
         where Convert.ToDateTime(c.data).CompareTo(left) >= 0
               && Convert.ToDateTime(c.data).CompareTo(right) <= 0
               && c.idsticker.Equals(x)
          group c by new { ((DateTime)c.data).Year, ((DateTime)c.data).Month }
                into groupMonthAvg
          select new {
              groupMonthAvg.Key.Year, 
              groupMonthAvg.Key.Month, 
              YearAverage = groupMonthAvg.Average(x=>x.Year),
              MonthAverage = groupMonthAvg.Average(x=>x.Month)
              };

答案 1 :(得分:1)

这应该这样做:

var query0 = from c in dc.Prices
             where Convert.ToDateTime(c.data).CompareTo(left) >= 0
                   && Convert.ToDateTime(c.data).CompareTo(right) <= 0
                   && c.idsticker.Equals(x)
              group c by new { ((DateTime)c.data).Year, ((DateTime)c.data).Month }
                    into groupMonthAvg
              select new { Year = groupMonthAvg.Key.Year, Month = groupMonthAvg.Key.Month, Average => groupMonthAvg.Average(i => i.value) };

答案 2 :(得分:1)

使用平均功能。

var query0 = from c in dc.Prices
             where Convert.ToDateTime(c.data).CompareTo(left) >= 0
                   && Convert.ToDateTime(c.data).CompareTo(right) <= 0
                   && c.idsticker.Equals(x)
              group c by new { ((DateTime)c.data).Year, ((DateTime)c.data).Month }
                    into groupMonthAvg
              select new
              {
                  years = groupMonthAvg.Key.Year,
                  months = groupMonthAvg.Key.Month,
                  prices = groupMonthAvg.Average(x=>x.value)
              };