C# 后台代码直接测试,代码如下:
//创建一个空表 DataTable dt = new DataTable(); dt.Columns.Add("日期", typeof(DateTime)); dt.Columns.Add("类别", typeof(String)); dt.Columns.Add("科室", typeof(String)); dt.Columns.Add("数量", typeof(double)); //3.通过行框架创建并赋值 dt.Rows.Add("2020-01-01", "门诊","内科",10); dt.Rows.Add("2020-01-01", "门诊", "外科", 20); dt.Rows.Add("2020-01-01", "门诊", "骨科", 30); dt.Rows.Add("2020-01-01", "住院", "内科病区", 40); dt.Rows.Add("2020-01-01", "住院", "小儿病区", 50); dt.Rows.Add("2020-01-02", "门诊", "内科", 60); dt.Rows.Add("2020-01-02", "门诊", "外科", 70); dt.Rows.Add("2020-01-02", "住院", "小儿病区", 80); var data = dt.AsEnumerable(); var typeName = ""; decimal typeSum = 0; //一、单柱数据 不需要对比 //1.按日期汇总数量 var s = data.GroupBy(r => r["日期"]).Select(g=>new { Name=g.Key,Sum=g.Sum(r=>(double)r["数量"])}); foreach (var sitem in s.ToList()) { //取出值进行使用 typeName =sitem.Name.ToString(); typeSum =Convert.ToDecimal(sitem.Sum.ToString()); } //2.按类别进行汇总 var s1 = data.GroupBy(r => r["类别"]).Select(g => new { Name = g.Key, Sum = g.Sum(r => (double)r["数量"]) }); foreach (var s1item in s1.ToList()) { //取出值进行使用 typeName = s1item.Name.ToString(); typeSum = Convert.ToDecimal(s1item.Sum.ToString()); } //3.按科室进行汇总 var s2 = data.GroupBy(r => r["科室"]).Select(g => new { Name = g.Key, Sum = g.Sum(r => (double)r["数量"]) }); foreach (var s2item in s2.ToList()) { //取出值进行使用 typeName = s2item.Name.ToString(); typeSum = Convert.ToDecimal(s2item.Sum.ToString()); } //二、具有对比性质的汇总 //1.相同时间点下 不同类别数量分别多少 var t = data.GroupBy(r=> new { 日期=r["日期"],类别= r["类别"] }).Select(g=>new {Name=g.Key.日期,tp = g.Key.类别,Sum=g.Sum(i=>(double)i["数量"]) }); //2.相同时间节点下 不同科室数量分别多少 var t1 = data.GroupBy(r => new { 日期 = r["日期"], 科室 = r["科室"] }).Select(g => new { Name = g.Key.日期, tp = g.Key.科室, Sum = g.Sum(i => (double)i["数量"]) });
程序最终获取的汇总数据示例如下图: