对于从相同数据源读取不同要求的数据,可以只读取一次数据库,用linq进行数据的分类。
数据库示例:
--优化前读取7此数据库 SELECT COUNT(DISTINCT p) FROM aa WITH(NOLOCK) WHERE DateDiff(dd, c, getdate())=0 SELECT COUNT(DISTINCT p) FROM aa WITH(NOLOCK) WHERE DateDiff(dd, c, getdate())=1 SELECT COUNT(DISTINCT p) FROM aa WITH(NOLOCK) SELECT SUM(at) FROM aa WITH(NOLOCK) WHERE s=30 SELECT MAX(at) FROM aa WITH(NOLOCK) WHERE s=30 SELECT SUM(at) FROM aa WITH(NOLOCK) WHERE s=10 SELECT SUM(at) FROM aa WITH(NOLOCK) WHERE s=30 and d=1 --优化后读取一次数据库 SELECT at,s,d,p,c FROM aa WITH(NOLOCK)
获取数据示例:
//代码优化读7次数据库,改为读一次数据库 var tempt = RB.GetAA(Config.ConStrRead); if (tempt != null&& tempt.Rows.Count>0) { var enumer = tempt.AsEnumerable(); var todayPhones= enumer.Where(m => SlConvert.TryToDateTime(m["c"]) >= DateTime.Today).Select(m => SlConvert.TryToInt64(m["Phone"])); outModel.TodayRecv = todayPhones.ToList().Distinct().Count(); //var yesterdayPhones = enumer.Where(m => SlConvert.TryToDateTime(m["c"]) >= DateTime.Today.AddDays(-1)).Select(m => SlConvert.TryToInt64(m["Phone"])); //outModel.YesterdayRecv = yesterdayPhones.ToList().Distinct().Count(); var totalPhones = enumer.Select(m => SlConvert.TryToInt64(m["p"])); outModel.TotalRecv = totalPhones.ToList().Distinct().Count(); var cashed = enumer.Where(m => SlConvert.TryToInt32(m["s"]) == 30).ToList(); var cashedAfterTaxMoney = cashed.Select(m => SlConvert.TryToInt64(m["at"])).ToList(); outModel.TotalSaveMoney = cashedAfterTaxMoney.Sum(); //outModel.ServerMoneyAll = cashed.Where(m => SlConvert.TryToInt32(m["d"]) == 1).Select(m => SlConvert.TryToInt64(m["at"])).Sum(); outModel.MaxRedBagMoney = cashedAfterTaxMoney.Max(); outModel.RestRedBagMoney = enumer.Where(m => SlConvert.TryToInt32(m["s"]) == 10).Select(m => SlConvert.TryToInt64(m["at"])).Sum(); }