比较复杂的SQL转Linq

2020-01-14 21:11发布

  1   仅仅作为自己的笔记
  2         /// <summary>
  3         /// *****-课堂资源统计
  4         /// </summary>
  5         /// <param name="subjectId"></param>
  6         /// <param name="secId"></param>
  7         /// <param name="startDate"></param>
  8         /// <param name="endDate"></param>
  9         /// <returns></returns>
 10         public IQueryable<ShowClassRoomResourceStatistics> GetClassRoomResourceStatistics(string subjectId, string secId, string startDate, string endDate)
 11         {
 12             //得到资源信息
 13             var gallerys = _guideLearnLogic.GetGallery().Where(s => s.isdel == 0);
 14             //得到资源文件夹信息
 15             var galleryDirs = _guideLearnLogic.GetGalleryDir().Where(s => s.isdel == 0);
 16             //资源操作记录
 17             var galleryLogs = _guideLearnLogic.GetGalleryLog().Where(s => s.act == "dn" && s.cll_id != null);
 18             //得到科目信息
 19             var subjects = _subjectLogic.GetSubject().Where(s => s.isdel == 0);
 20             //得到人的信息
 21             var persons = _personLogic.GetPersonnel().Where(s => s.isdel == 0 && s.per_role == 30);
 22             //如果科目编号不为空的话
 23             if (!string.IsNullOrEmpty(subjectId))
 24             {
 25                 subjects = subjects.Where(s => s.sub_id == subjectId);
 26             }
 27             //如果年级不为空的话
 28             if (!string.IsNullOrEmpty(secId))
 29             {
 30                 subjects = subjects.Where(s => s.sec_id == secId);
 31             }
 32             //时间搜索
 33             if (!string.IsNullOrEmpty(startDate) && !string.IsNullOrEmpty(endDate))
 34             {
 35                 var formatStartDate = Convert.ToDateTime(startDate);
 36                 var formatEndDate = Convert.ToDateTime(endDate);
 37                 galleryLogs = galleryLogs.Where(s => Convert.ToDateTime(s.cdate) >= formatStartDate && Convert.ToDateTime(s.cdate) <= formatEndDate);
 38             }
 39             if (galleryLogs != null && galleryLogs.Count() > 0)
 40             {
 41                 var data = from galleryLog in galleryLogs
 42 
 43                            join gallery in gallerys on galleryLog.galleryid equals gallery.galleryid into tempGallerys
 44                            from tempGallery in tempGallerys.DefaultIfEmpty()
 45 
 46                            join galleryDir in galleryDirs on tempGallery.gallerydirid equals galleryDir.gallerydirid into tempGalleryDirs
 47                            from tempGalleryDir in tempGalleryDirs.DefaultIfEmpty()
 48 
 49                            join subject in subjects on tempGalleryDir.subjectid equals subject.sub_id into tempSubjects
 50                            from tempSubject in tempSubjects.DefaultIfEmpty()
 51 
 52                            join person in persons on galleryLog.per_id equals person.per_id into tempPersons
 53                            from tempPerson in tempPersons.DefaultIfEmpty()
 54                            group tempPerson by new { galleryLog.per_id, tempPerson.per_userid, tempPerson.per_name, galleryLog.galleryid } into g
 55                            orderby g.ToList().Count() descending
 56                            select new ShowClassRoomResourceStatistics
 57                            {
 58                                per_userid = g.Key.per_userid,
 59                                per_name = g.Key.per_name,
 60                                count = g.Count(),
 61                                galleryid = g.Key.galleryid,
 62                            };
 63                 return data;
 64             }
 65             return null;
 66         }
 67         /// <summary>
 68         /// *****-教学手段
 69         /// </summary>
 70         /// <param name="subjectId"></param>
 71         /// <param name="secId"></param>
 72         /// <param name="startDate"></param>
 73         ///  <param name="endDate"></param>
 74         /// <returns></returns>
 75         public List<ShowTeacherDevicesResult> GetTeachingDevices(string subjectId, string secId, string startDate, string endDate)
 76         {
 77             if (string.IsNullOrEmpty(subjectId) || string.IsNullOrEmpty(secId))
 78             {
 79                 return null;
 80             }
 81             //班级记录
 82             var classesLogs = _classesLogic.GetClassLog();
 83             var functionRecords = _guideLearnLogic.GetFunctionRecord();
 84             //人员信息
 85             var personnel = _personLogic.GetPersonnel().Where(s => s.isdel == 0);
 86             //科目信息
 87             var subjects = _subjectLogic.GetSubject().Where(s => s.isdel == 0);
 88 
 89             if (classesLogs != null)
 90             {
 91                 var data = from L in classesLogs
 92                            join R in functionRecords on L.cll_id equals R.cll_id into tempR
 93                            from RData in tempR.DefaultIfEmpty()
 94 
 95                            join P in personnel on L.per_id equals P.per_id into tempP
 96                            from Pdata in tempP.DefaultIfEmpty()
 97 
 98                            join S in subjects on L.sub_id equals S.sub_id into tempS
 99                            from SData in tempS.DefaultIfEmpty()
100                            where SData.sub_id == subjectId && Pdata.isdel == 0 && SData.isdel == 0
101                            select new ShowTeachingDevices
102                            {
103                                per_id = Pdata.per_id,
104                                per_name = Pdata.per_name,
105                                sub_name = SData.sub_name,
106                                fcd_code = RData.fcd_code.StartsWith("C") ? "C" : (
107                                            RData.fcd_code.StartsWith("D") ? "D" : "ELSE"),
108 
109                                sub_id = SData.sub_id,
110                                sec_id = SData.sec_id,
111                                cll_cdate = L.cll_cdate,
112 
113                            };
114                 if (!string.IsNullOrEmpty(subjectId))
115                 {
116                     data = data.Where(c => c.sub_id == subjectId);
117                 }
118                 if (!string.IsNullOrEmpty(secId))
119                 {
120                     data = data.Where(c => c.sec_id == secId);
121                 }
122                 //时间搜索
123                 if (!string.IsNullOrEmpty(startDate) && !string.IsNullOrEmpty(endDate))
124                 {
125                     var formatStartDate = DateTime.Parse(startDate);
126                     var formatEndDate = DateTime.Parse(endDate);
127                     data = data.Where(c => c.cll_cdate >= formatStartDate && c.cll_cdate <= formatEndDate);
128                 }
129                 /*
130               SELECT per_id,per_name, SUM(count_num),fcd_code
131                      FROM(
132                      SELECT P.per_id,P.per_name, COUNT(1) AS count_num, CASE WHEN R.fcd_code LIKE 'C%' THEN 'C' WHEN R.fcd_code LIKE 'D%' THEN  'D'   ELSE    'ELSE'   END   fcd_code
133                      FROM class_log L
134                      LEFT JOIN function_record R ON R.cll_id=L.cll_id
135                      LEFT JOIN personnel P ON L.per_id= P.per_id
136                      LEFT JOIN subject S ON L.sub_id=S.sub_id
137                      WHERE L.sub_id='95301ab4-1e5f-11e5-b161-1c4bd611580c' AND L.cll_cdate BETWEEN '2016-01-10' AND '2020-01-10'
138                      GROUP BY P.per_id,R.fcd_code
139                      ORDER BY L.cll_cdate DESC
140                      )T
141                      GROUP BY per_id,fcd_code;
142                  */
143 
144                 data = data.OrderByDescending(c => c.cll_cdate);
145                 var groupByData = (from G in data
146                                    group G by new
147                                    {
148                                        G.per_id,
149                                        G.per_name,
150                                        G.fcd_code
151                                    } into G
152                                    select new ShowTeacherDevicesResult
153                                    {
154                                        per_id = G.Key.per_id,
155                                        per_name = G.Key.per_name,
156                                        fcd_code = G.Key.fcd_code,
157                                        count = G.Count()
158                                    }).ToList();
159 
160                 var dataList = (from T in groupByData
161                                 group T by new
162                                 {
163                                     T.per_id,
164                                     T.per_name,
165                                     T.fcd_code
166                                 } into Td
167                                 let sumCount = Td.Where(c => c.per_id == Td.Key.per_id && c.fcd_code == Td.Key.fcd_code).Sum(c => c.count)
168                                 select new ShowTeacherDevicesTemp
169                                 {
170                                     per_id = Td.Key.per_id,
171                                     per_name = Td.Key.per_name,
172                                     fcd_code = Td.Key.fcd_code,
173                                     count = sumCount
174                                 }).ToList();
175                 if (dataList != null && dataList.Count > 0)
176                 {
177                     List<ShowTeacherDevicesResult> result = new List<ShowTeacherDevicesResult>();
178                     foreach (ShowTeacherDevicesTemp item in dataList)
179                     {
180                         ShowTeacherDevicesResult r = new ShowTeacherDevicesResult();
181                         r.per_id = item.per_id;
182                         r.per_name = item.per_name;
183                         r.fcd_code = item.fcd_code=="C"?"富媒体":(item.fcd_code=="D"?"教学工具":"互动工具");
184                         int pcount = dataList.Where(c => c.per_id == item.per_id).Count();//多少个分组
185                         int itemCount = item.count == 0 ? 1 : item.count;
186                         int totalCount = item.count;
187                         if (pcount >= 2)
188                             totalCount = dataList.Where(c => c.per_id == item.per_id).Sum(c => c.count);
189                         r.count = itemCount;
190                         r.perfentRate = $"{(itemCount / totalCount * 1.0 * 100).ToString("f2")}%";
191                         result.Add(r);
192                     }
193                     return result;
194                 }
195 
196             }
197 
198             return null;
199         }
200 
201         /// <summary>
202         /// *****-教学准备
203         /// </summary>
204         /// <param name="subjectId"></param>
205         /// <param name="secId"></param>
206         /// <param name="startDate"></param>
207         /// <param name="endDate"></param>
208         /// <returns></returns>
209         public async Task<List<ShowTeacherCourseResult>> GetTeachingPreparation(string subjectId, string secId, string startDate, string endDate)
210         {
211             if (string.IsNullOrEmpty(subjectId))
212             {
213                 return null;
214             }
215             var classLogic = _classesLogic.GetClassLog();
216             var courseLogic = _courseLogic.GetCourse().Where(c => c.isdel == 0);
217             var functionRecordLogic = _guideLearnLogic.GetFunctionRecord();
218             var personnelLgic = _personLogic.GetPersonnel().Where(c => c.isdel == 0);
219             var subjectLogic = _subjectLogic.GetSubject().Where(c => c.isdel == 0);
220 
221             #region 没有分组的所有过滤的数据
222             var data = (from L in classLogic
223                         join C in courseLogic on L.cou_id equals C.cou_id into Ctemp
224                         from Cdata in Ctemp.DefaultIfEmpty()
225 
226                         join R in functionRecordLogic on L.cll_id equals R.cll_id
227 
228                         join P in personnelLgic on L.per_id equals P.per_id
229 
230                         join S in subjectLogic on L.sub_id equals S.sub_id into Stemp
231                         from Sdata in Stemp.DefaultIfEmpty()
232 
233                         orderby Cdata.cdate descending
234                         where (new string[] { "in", "ou" }).Contains(L.cll_type)
235                         select new ShowTeachingPreparationBase
236                         {
237                             sub_id = Sdata.sub_id,
238                             sub_name = Sdata.sub_name,
239                             cll_id = L.cll_id,
240                             cll_type = L.cll_type,
241                             level = Cdata.level,
242                             per_id = Cdata.per_id,
243                             per_name = P.per_name,
244                             per_userid = P.per_userid,
245                             cll_edate = L.cll_edate,
246                             cll_cdate = L.cll_cdate,
247                             fcd_code = R.fcd_code.StartsWith("C") ? "C" : (R.fcd_code.StartsWith("D") ? "D" : "ELSE"),
248                             sec_id = Sdata.sec_id,
249                             cdate = R.cdate
250                         });
251 
252             //科目不为空时
253             if (!string.IsNullOrEmpty(subjectId))
254             {
255                 data = data.Where(c => c.sub_id == subjectId);
256             }
257             //年段,小学,中学,高中...
258             if (!string.IsNullOrEmpty(secId))
259             {
260                 data = data.Where(c => c.sec_id == secId);
261             }
262             //开始与结束时间
263             if (!string.IsNullOrEmpty(startDate) && !string.IsNullOrEmpty(endDate))
264             {
265                 var formatStartDate = Convert.ToDateTime(startDate);
266                 var formatEndDate = Convert.ToDateTime(endDate);
267                 data = data.Where(c => c.cdate >= formatStartDate && c.cdate <= formatEndDate);
268                 data = data.Where(c => c.cll_cdate >= formatStartDate && c.cll_edate <= formatEndDate);
269             }
270             #endregion
271 
272             #region 分组后的数据
273             var tempdata = (
274                 from tt in data
275                 where tt.per_id != null
276                 group tt by new
277                 {
278                     tt.cll_id,
279                     tt.sub_id,
280                     tt.per_id,
281                     tt.per_name,
282                     tt.level,
283                     tt.cll_type,
284                     tt.fcd_code
285 
286                 } into G
287                 select new ShowTeachingPreparationTemp
288                 {
289                     cll_id = G.Key.cll_id,
290                     per_id = G.Key.per_id,
291                     per_name = G.Key.per_name,
292                     sub_id = G.Key.sub_id,
293                     level = G.Key.level,
294                     cll_type = G.Key.cll_type,
295                     fcd_code = G.Key.fcd_code,
296                     count_num = G.Count()
297                 }).ToList();
298             // 按照老系统的数据展示,必须要分组两次
299             var newGroup = (from TD in tempdata
300                             group TD by new
301                             {
302                                 TD.sub_id,
303                                 TD.per_id,
304                                 TD.per_name,
305                                 TD.level,
306                                 TD.cll_type,
307                                 TD.fcd_code,
308 
309                             } into DD
310                             select new ShowTeachingPreparationTemp
311                             {
312                                 per_id = DD.Key.per_id,
313                                 per_name = DD.Key.per_name,
314                                 sub_id = DD.Key.sub_id,
315                                 level = DD.Key.level,
316                                 cll_type = DD.Key.cll_type,
317                                 fcd_code = DD.Key.fcd_code,
318                                 count_num = DD.Count()
319 
320                             }).ToList();
321 
322             #endregion
323 
324             List<ShowTeacherCourseResult> resultList = new List<ShowTeacherCourseResult>();
325             // Key 的分组的总的次数
326             int totalRowCount = newGroup.Count;
327 
328             //-有做数据的合并(同一个老师的相同的课程会存在多条数据,如相同老师的相同课程相同年段 C,D,ELSE的情况需要合并)
329             for (int i = 0; i < totalRowCount; i++)
330             {
331                 var sub_id = newGroup[i].sub_id;
332                 var level = newGroup[i].level;//年级
333                 var cll_type = newGroup[i].cll_type;
334                 var fcd_code = newGroup[i].fcd_code;
335                 var per_id = newGroup[i].per_id;
336                 var per_name = newGroup[i].per_name;//课程教师
337 
338                 //获取当前这个老师的所有 cll_id
339                 string[] getcll_idList = tempdata.Where(c => c.per_id == per_id && c.sub_id == sub_id && c.level == level).Select(c => c.cll_id).ToArray();
340                 var M = tempdata.Where(c => c.per_id == per_id && c.sub_id == sub_id && c.level == c.level).ToList();
341                 int nowGroupCount = M.Count();//登录的次数
342                 ShowTeacherCourseResult re = new ShowTeacherCourseResult();
343                 await AssemblingModel(M, nowGroupCount, re, getcll_idList, per_id, level, sub_id, per_name, cll_type);
344                 resultList.Add(re);
345             }
346             return resultList;
347         }
348 
349         private async Task AssemblingModel(List<ShowTeachingPreparationTemp> M, int nowGroupCount, ShowTeacherCourseResult re, string[] cll_idList, string per_id, string level, string sub_id, string per_name, string cll_type)
350         {
351             re.level = level;//年*
352             re.sub_id = sub_id;
353             re.per_id = per_id;
354             re.per_name = per_name;//姓名
355             re.loginCount = nowGroupCount.ToString(); //登录的次数
356             string type = cll_type;
357             re.loginCount = type == "in" ? $"{nowGroupCount}/0" : $"0/{nowGroupCount}";
358             //获取到这个人的该课程的所有的cll_id,方便来获取总的时间
359             var getCllid_list = M.Select(c => new cll_idList { cll_id = c.cll_id }).ToList();
360 
361             //使用的时间
362             string havaUseTime = await Task.Factory.StartNew(() => ((from T in _classesLogic.GetClassLog()
363                                                                      where cll_idList.Contains(T.cll_id)
364                                                                      select new { T.cll_edate, T.cll_cdate }).ToList().Sum(c => (c.cll_edate - c.cll_cdate).TotalSeconds / 60.0).ToString("f2")));
365 
366             re.havaUseTime = type == "in" ? $"{havaUseTime}/0" : $"0/{havaUseTime}";
367             //C *媒体
368             int dataC = GetDataCDEDataRateCount(M, "C", level, per_id, sub_id);
369             //D 教*工具
370             int dataD = GetDataCDEDataRateCount(M, "D", level, per_id, sub_id);
371             //ELSE 互*工具
372             int dataE = GetDataCDEDataRateCount(M, "ELSE", level, per_id, sub_id);
373 
374             int totalCount = dataC + dataD + dataE;
375 
376             string dataC_PercentRage = $"{(dataC * 1.0 * 100 / totalCount).ToString("f2")}";
377             string dataD_PercentRage = $"{(dataD * 1.0 * 100 / totalCount).ToString("f2")}";
378             string dataE_PercentRage = $"{(dataE * 1.0 * 100 / totalCount).ToString("f2")}";
379 
380             re.richMedia = type == "in" ? $"{dataC_PercentRage}%/0.00%" : $"0.00%/{dataC_PercentRage}%";
381             re.teacherTool = type == "in" ? $"{dataD_PercentRage}%/0.00%" : $"0.00%/{dataD_PercentRage}%";
382             re.interactiveTools = type == "in" ? $"{dataE_PercentRage}%/0.00%" : $"0.00%/{dataE_PercentRage}%";
383         }
384 
385         private static int GetDataCDEDataRateCount(List<ShowTeachingPreparationTemp> M, string fcd_code, string level, string per_id, string sub_id)
386         {
387             return M.Where(c => c.fcd_code == fcd_code && c.level == level && c.per_id == per_id && c.sub_id == sub_id).Count();
388         }
标签: