SELECT COUNT(l.LogSeq), date_format(l.CreateDate,'%Y-%m') CreateDateByMonth FROM LOL l WHERE l.CreateDate>='2017-1-1' AND l.CreateDate<='2017-8-16' GROUP BY CreateDateByMonth
把数据按照月份分组获取所需要的数据SQL语句变为EF,错误的写法:
//先做基本查询 var querySql = from l in LOL select new LOL { LogSeq = l.LogSeq, CreateDate = l.CreateDate }; //条件在基本的查询中完成 if (query.CreateDateStart != null) { querySql = querySql.Where(t => t.CreateDate >= query.CreateDateStart); } if (query.CreateDateEnd != null) { querySql = querySql.Where(t => t.CreateDate <= query.CreateDateEnd); } //然后把基本的条件过滤后的查询语句去分组 var ret = querySql.GroupBy(t => new { t.CreateDate }).Select(s => new LOL { LogSeq = s.Sum(m => m.LogSeq), CreateDate = s.Key.CreateDate });
这样没有对数据进行安月分组,如果有时分秒的时候分组失败,如果把时间类型的字段tostring(“”yyyy-MM-dd“”)又不会被linq所承认,这时候需要把时间拆成年,月,日这样的多个字段。返回列表后再去拼接形成一个日期,正确写法如下:
//先做基本查询,这里不可以使用select new LogClinicDataOperationInfo这样的写法,需要匿名去写linq var querySql = from l in _logClinicDataOperationRepository.Table select new { LogSeq = l.LogSeq, CreateDate=l.CreateDate, Year = l.CreateDate.Value.Year, Mounth= l.CreateDate.Value.Month, }; //条件在基本的查询中完成 if (query.CreateDateStart != null) { querySql = querySql.Where(t => t.CreateDate >= query.CreateDateStart); } if (query.CreateDateEnd != null) { querySql = querySql.Where(t => t.CreateDate <= query.CreateDateEnd); } //然后把基本的条件过滤后的查询语句去分组,返回一条日期的年和月 var result = querySql.GroupBy(t => new { t.Year, t.Mounth }).Select(s => new LogClinicDataOperationInfo { Year = s.Key.Year, Mounth = s.Key.Mounth, Count = s.Count() });