如何按月份&id查询sql以获得sum

wj8zmpe1  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(395)

我的表格数据如下:

我想将asp.net表显示为:

下面是按组月份和商店代码获取数据的代码

var gridData = data
                    .GroupBy(
                        x => new {
                            Convert.ToDateTime(x.InspectedAt).Month,
                            Convert.ToDateTime(x.InspectedAt).Year,
                            x.ShopCode
                        }
                    )
                    .Select(x => new InspectionSearchData
                    {
                        month = x.Key.Month,
                        shopCode = x.Key.ShopCode,
                        total = (int)x.Sum(a => a.PerformCount)
                    })
                    .OrderBy(x => x.month)
                    .ToList();

但我不知道如何在asp.NETHTML表中显示像图2这样的数据。
有人能建议如何在asp.net中这样做吗?
提前谢谢。

50pmv0ei

50pmv0ei1#

创建数据透视表:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("shopcode", typeof(string));
            dt.Columns.Add("month", typeof(int));
            dt.Columns.Add("count", typeof(int));

            dt.Rows.Add(new object[] { "007", 4, 1 });
            dt.Rows.Add(new object[] { "007", 6, 2 });
            dt.Rows.Add(new object[] { "009", 7, 1 });
            dt.Rows.Add(new object[] { "010", 8, 1 });
            dt.Rows.Add(new object[] { "010", 5, 1 });
            dt.Rows.Add(new object[] { "011", 9, 5 });

            int minMonth = dt.AsEnumerable().Min(x => x.Field<int>("month"));
            int maxMonth = dt.AsEnumerable().Max(x => x.Field<int>("month"));

            DataTable pivotTable = new DataTable();
            pivotTable.Columns.Add("shopcode", typeof(string));
            for (int i = minMonth; i <= maxMonth; i++)
            {
                pivotTable.Columns.Add(i.ToString(), typeof(string));
            }

            var groups = dt.AsEnumerable().GroupBy(x => x.Field<string>("shopcode"));

            foreach(var group in groups)
            {
                DataRow newRow = pivotTable.Rows.Add();
                newRow["shopcode"] = group.Key;
                var months = group.GroupBy(x => x.Field<int>("month"));
                foreach(var month in months)
                {
                    newRow[month.Key.ToString()] = month.Sum(x => x.Field<int>("count"));
                }
                for(int i = minMonth; i <= maxMonth; i++)
                {
                    if(newRow[i.ToString()] == DBNull.Value)
                    {
                        newRow[i.ToString()] = 0;
                    }
                }
            }
        }
    }
}

相关问题