Asp.net 관리 정보 시스템 에서 데이터 통계 기능 의 실현 방법

데이터 통 계 는 모든 시스템 에서 필수 적 인 기능 으로 지도자 에 게 통계 데 이 터 를 보고 하고 업무 수행 에 필요 한 진전 데 이 터 를 보고 할 때 매우 유용 하 다.
내 가 보기에 통계 모듈 은 다음 과 같은 기능 을 실현 해 야 한다.
4.567917.자주 사용 하 는 조회 의 통계 결 과 를 나 타 낼 수 있다4.567917.표 형식 일 수도 있 고 도형 형식 일 수도 있 습 니 다.도형 이 라면 여러 가지 형식 으로 표시 할 수 있 습 니 다.
4.567917.통계 조회 결과 숫자 나 백분율 을 클릭 하면 상세 한 데 이 터 를 나 타 낼 수 있다4.567917.조회 조건,선별 조건,조별 조건,정렬 등 을 자 유 롭 게 조합 할 수 있다4.567917.통계 결 과 는 실시 간 으로 미리 보 는 것 이 좋 습 니 다4.567917.조회 통 계 는 다음 에 통계 조회 결 과 를 직접 호출 하고 표시 할 수 있 도록 저장 할 수 있다4.567917.저 장 된 조회 통계 에 대해 다음 호출 시 유연 한 선별 수단 에 따라 조회 결 과 를 선별 할 수 있다4.567917.인터페이스 가 간결 하고 직관 적 으로 해 야 하기 때문에 컴퓨터 를 잘 모 르 는 조작 원 이라도 편리 하 게 사용 할 수 있다4.567917.복잡 한 조회 에 대해 배경 에 Sql 을 직접 쓰 거나 Sp 를 호출 하여 데 이 터 를 낼 수 있 습 니 다......
자,다음은 실제 환경 에서 의 실현 과 응용 이다.
이것 은 한 학생 의 취업 시스템 으로 학생 들 이 서로 다른 시기 에 자신의 졸업 행방 을 등록 하기 때문에 시간 대별 로 통 계 된 데 이 터 는 다르다.데이터 시트 에는 100 여 개의 필드 가 있다.
우선,우 리 는 데이터베이스 에 표 값 함 수 를 구축 하여 서로 다른 시간 에 따라 데 이 터 를 반환 할 수 있 고 표 도 보기 의 역할 을 하 며 매개 변수 표 의 값 을 결과 에 직접 포함 시 킬 수 있 습 니 다.

ALTER FUNCTION [dbo].[Get.............]
( 
 @gxsj datetime
)
RETURNS TABLE 
AS
RETURN 
(
 select t1.*, 
 dbo.depacode.xymc, 
 CASE t1.xldm WHEN '01' THEN '  ' WHEN '11' THEN '  ' WHEN '25' THEN '   ' WHEN '31' THEN '  ' WHEN '41' THEN '  ' WHEN '61' THEN '  ' ELSE '' END AS xlmc, 
 CASE WHEN LEFT(t1.sydqdm, 2) IN ('11', '12', '13', '21', '31', '32', '33', '35', '37', '44', '46', '71', '81', '82') THEN '  ' 
 WHEN LEFT(t1.sydqdm, 2) IN ('14', '22', '23', '34', '36', '41', '42', '43') THEN '  ' 
 WHEN LEFT(t1.sydqdm, 2) IN ('15', '45', '51', '50', '52', '53', '54', '61', '62', '65', '63', '64') THEN '  ' ELSE '' END AS sydq, 
 sydq.dwdqmc AS sysf,
 CASE WHEN LEFT(t1.dwdqdm, 2) IN ('11', '12', '13', '21', '31', '32', '33', '35', '37', '44', '46', '71', '81', '82') THEN '  ' 
 WHEN LEFT(t1.dwdqdm, 2) IN ('14', '22', '23', '34', '36', '41', '42', '43') THEN '  ' 
 WHEN LEFT(t1.dwdqdm, 2) IN ('15', '45', '51', '50', '52', '53', '54', '61', '62', '65', '63', '64') THEN '  ' ELSE '' END AS dwdq, 
  dwdq.dwdqmc AS dwsf, dbo.Entcode.hyname, 
 dbo.hydygx.hymldm, dbo.hydygx.hyml, 
 CASE t1.xbdm WHEN 1 THEN ' ' WHEN 2 THEN ' ' ELSE ' ' END AS xbmc,
 [mzdmb].[nation] AS mzmc,
 [EjByqxdmb].[Ejbyqxmc], dbo.byqxdygx.jybbyqx, t1.gn500 AS jybdwxzdm,
 CASE t1.knslbdm WHEN '7' THEN '    、       ' WHEN '6' THEN '       ' WHEN '5' THEN '       ' WHEN '4' THEN '  ' WHEN '3' THEN '       ' WHEN '2' THEN '    ' WHEN '1' THEN '    ' ELSE '    ' END AS Knslb
 from [table] as t1 
 LEFT OUTER JOIN
 dbo.depacode ON t1.xydm = dbo.depacode.xydm LEFT OUTER JOIN
 dbo.dwdq AS sydq ON LEFT(t1.sydqdm, 2) + '0000' = sydq.dwdqdm LEFT OUTER JOIN
 dbo.dwdq AS dwdq ON LEFT(t1.dwdqdm, 2) + '0000' = dwdq.dwdqdm LEFT OUTER JOIN
 dbo.Entcode ON t1.hylb = dbo.Entcode.hycode LEFT OUTER JOIN
 dbo.hydygx ON t1.hylb = dbo.hydygx.hydldm LEFT OUTER JOIN
 [mzdmb] ON t1.mzdm = [mzdmb].[mzdm] LEFT OUTER JOIN
 [EjByqxdmb] ON t1.byqx2 = [EjByqxdmb].[Ejbyqxdm] LEFT OUTER JOIN
 dbo.byqxdygx ON t1.byqx = dbo.byqxdygx.shbyqx AND 
 t1.dwxzdm = dbo.byqxdygx.shdwxzdm
 where [gxsj] <= dateadd(day,1,@gxsj) and HisId in 
 (SELECT TOP 1 HisId FROM [table]
 WHERE [gxsj] <= dateadd(day,1,@gxsj) and xsxh = t1.xsxh
 and bynf = t1.bynf and t1.byqx not in ('08','05','11')
 ORDER BY [gxsj] DESC)
)
이렇게 하면 우 리 는 8 월 25 일 마감 일의 데 이 터 를 조회 할 수 있다.
다음은 인터페이스 디자인 입 니 다.저 희 는 jequery-ui 에서 dropable\dragable 컨트롤 을 사용 하여 필드 를 인터페이스 에 배열 하고 해당 도 메 인 에 직접 끌 어 다 놓 으 면 통 계 를 할 수 있 습 니 다.
그룹 필드 를 제외 하고 디 스 플레이 필드 는 구체 적 인 값 에 따라 통계 적 으로 여과 하여 다 중 그룹 통계 기능 을 할 수 있 습 니 다.


 맨 위 에 있 는 칸 은 데이터 선별 이 고 시스템 에 저 장 된 조회(표 조회 와 도형 조회 로 나 뉜 다)입 니 다.저 장 된 조 회 를 누 르 면 조회 결 과 를 직접 내 고 저 장 된 조 회 를 삭제 할 수 있 습 니 다.아래 는 사용자 정의 조회 입 니 다.위 는 한 줄 의 조건 이 고 그 다음 에 끌 수 있 는 필드 입 니 다.필드 를 그룹 열 로 끌 면 필드 이름 을 표시 합 니 다.디 스 플레이 열 로 끌 어 다 놓 으 면 표 시 된 데이터 의 구체 적 인 값 을 그룹 별로 선별 하여 통계 할 수 있 습 니 다.아래 는 소계,총 계 를 표시 할 지,어떤 방식 으로 도 표를 표시 할 지 옵션 입 니 다.
표 형식의 디 스 플레이 통 계 를 보면 모든 수 치 는 팝 업 상 자 를 클릭 하여 상세 한 상황 을 표시 할 수 있 고 맨 아래 에 조회 조건 을 저장 하고 도형 으로 표시 할 수 있 습 니 다.


도형 의 전시:



다음은 핵심 클래스 Inquire Helper.cs 입 니 다.
필드 실체 클래스(부분)

[Serializable]
 [XmlInclude(typeof(BYNF_InquireField))]
 [XmlInclude(typeof(Count_InquireField))]
 [XmlInclude(typeof(XYMC_InquireField))]
 [XmlInclude(typeof(ZYMC_InquireField))]
 [XmlInclude(typeof(SZBJ_InquireField))]
 [XmlInclude(typeof(FDY_InquireField))]
 [XmlInclude(typeof(XL_InquireField))]
 [XmlInclude(typeof(SYDQ_InquireField))]
 [XmlInclude(typeof(SYSF_InquireField))]
 [XmlInclude(typeof(DWDQ_InquireField))]
 [XmlInclude(typeof(DWSF_InquireField))]
 [XmlInclude(typeof(HYML_InquireField))]
 [XmlInclude(typeof(HYDL_InquireField))]
 [XmlInclude(typeof(XBMC_InquireField))]
 [XmlInclude(typeof(MZMC_InquireField))]
 [XmlInclude(typeof(BYQX_InquireField))]
 [XmlInclude(typeof(KNSLB_InquireField))]
 [XmlInclude(typeof(ZYDKL_InquireField))]
 [XmlInclude(typeof(DWXZ_InquireField))]
 [XmlInclude(typeof(EJBYQXMC_InquireField))]
 [XmlInclude(typeof(GZ_InquireField))]
 [XmlInclude(typeof(WYJE_InquireField))]
 public abstract class InquireFieldBase
 {
  public InquireFieldBase()
  {
   FieldItems = this.GetInquireItemsByInquireType();
  }
  [XmlAttribute]
  public int FieldDisplayOrder { get; set; }
  [XmlAttribute]
  public string FieldName { get; set; }
  [XmlAttribute]
  public string DbName { get; set; }
  [XmlAttribute]
  public bool IsAggregate { get; set; }
  [XmlAttribute]
  public InquireHelper.FieldType FieldType { get; set; }
  //  highchart  
  [XmlAttribute]
  public bool IsNameField { get; set; }
  //        
  [XmlAttribute]
  public bool IsPercent { get; set; }
  [XmlIgnore]
  public List<string> FieldItems { get; set; }
  public List<string> FieldValue { get; set; }
  public bool? OrderByAsc { get; set; }
 }
 [Serializable]
 public class BYNF_InquireField : InquireFieldBase
 {
  public BYNF_InquireField()
  {
   FieldDisplayOrder = 1;
   FieldName = "    ";
   DbName = "BYNF";
  }
 }
 [Serializable]
 public class XYMC_InquireField : InquireFieldBase
 {
  public XYMC_InquireField()
  {
   FieldDisplayOrder = 5;
   FieldName = "    ";
   DbName = "XYMC";
  }
 }
 [Serializable]
 public class ZYMC_InquireField : InquireFieldBase
 {
  public ZYMC_InquireField()
  {
   FieldDisplayOrder = 6;
   FieldName = "    ";
   DbName = "ZYMC";
  }
 }
 [Serializable]
 public class SZBJ_InquireField : InquireFieldBase
 {
  public SZBJ_InquireField()
  {
   FieldDisplayOrder = 7;
   FieldName = "    ";
   DbName = "SZBJ";
  }
 }
 [Serializable]
 public class FDY_InquireField : InquireFieldBase
 {
  public FDY_InquireField()
  {
   FieldDisplayOrder = 8;
   FieldName = "   ";
   DbName = "FDY";
  }
 }
 [Serializable]
 public class XL_InquireField : InquireFieldBase
 {
  public XL_InquireField()
  {
   FieldDisplayOrder = 9;
   FieldName = "  ";
   DbName = "XLMC";
  }
 }
 [Serializable]
 public class SYDQ_InquireField : InquireFieldBase
 {
  public SYDQ_InquireField()
  {
   FieldDisplayOrder = 10;
   FieldName = "    ";
   DbName = "SYDQ";
  }
 }
 [Serializable]
 public class SYSF_InquireField : InquireFieldBase
 {
  public SYSF_InquireField()
  {
   FieldDisplayOrder = 11;
   FieldName = "    ";
   DbName = "SYSF";
  }
 }
 [Serializable]
 public class DWDQ_InquireField : InquireFieldBase
 {
  public DWDQ_InquireField()
  {
   FieldDisplayOrder = 12;
   FieldName = "    ";
   DbName = "DWDQ";
  }
 }
 [Serializable]
 public class DWSF_InquireField : InquireFieldBase
 {
  public DWSF_InquireField()
  {
   FieldDisplayOrder = 13;
   FieldName = "    ";
   DbName = "DWSF";
  }
 }
제어 클래스

public static class InquireHelper
 {
  public static List<InquireFieldBase> GetSubInquireList()
  {
   var inquires = new List<InquireFieldBase>();
   var subTypeQuery = from t in Assembly.GetExecutingAssembly().GetTypes()
        where IsSubClassOf(t, typeof(InquireFieldBase))
        select t;
   foreach (var type in subTypeQuery)
   {
    InquireFieldBase obj = CreateObject(type.FullName) as InquireFieldBase;
    if (obj != null)
    {
     inquires.Add(obj);
    }
   }
   return inquires;
  }
  static bool IsSubClassOf(Type type, Type baseType)
  {
   var b = type.BaseType;
   while (b != null)
   {
    if (b.Equals(baseType))
    {
     return true;
    }
    b = b.BaseType;
   }
   return false;
  }
  /// <summary>
  ///     (     )
  /// </summary>
  /// <param name="typeName">   </param>
  /// <returns>     ,     null</returns>
  public static object CreateObject(string typeName)
  {
   object obj = null;
   try
   {
    Type objType = Type.GetType(typeName, true);
    obj = Activator.CreateInstance(objType);
   }
   catch (Exception ex)
   {
   }
   return obj;
  }
  public static List<InquireFieldBase> BindCondition(this List<InquireFieldBase> conditions, string conditionName, List<string> values)
  {
   var condition = conditions.FirstOrDefault(c => c.GetType().Name == conditionName && c.FieldType == FieldType.ConditionField);
   if (condition == null)
   {
    condition = CreateObject("BLL." + conditionName) as InquireFieldBase;
    condition.FieldType = FieldType.ConditionField;
    conditions.Add(condition);
   }
   condition.FieldValue = values;
   return conditions;
  }
  //public static List<InquireFieldBase> BindCondition(this List<InquireFieldBase> conditions, string conditionName, string range1, string range2)
  //{
  // var condition = conditions.FirstOrDefault(c => c.GetType().Name == conditionName && c.FieldType == FieldType.ConditionField);
  // if (!string.IsNullOrEmpty(range2)&&!string.IsNullOrEmpty(range1))
  // {
  //  if (condition == null)
  //  {
  //   condition = CreateObject("BLL." + conditionName) as InquireFieldBase;
  //   condition.FieldType = FieldType.ConditionField;
  //   conditions.Add(condition);
  //  }
  //  condition.FieldValue = string.Concat(condition.DbName,
  //   " between to_date('", range1, "', 'yyyy-mm-dd hh24:mi:ss') and to_date('", range2,
  //   "', 'yyyy-mm-dd hh24:mi:ss')");
  // }
  // return conditions;
  //}
  public static DataTable GetDataTable(StatisticsInquire inquire)
  {
   var inquireCond = new List<string>();
   inquire.InquireFields.Where(f => f.FieldType == InquireHelper.FieldType.GroupField).ToList()
    .ForEach(f =>
    {
     if (!f.IsAggregate)
     {
      inquireCond.Add(string.Concat(f.DbName, " AS ", f.FieldName));
     }
    });
   inquire.InquireFields.Where(f => f.FieldType == FieldType.DisplayField).ToList().ToList()
    .ForEach(f => {
     if (f.IsAggregate)
     {
      inquireCond.Add(string.Concat(f.DbName, " AS ", f.FieldName));
     }
     else
     {
      if (f.IsPercent)
      {
       inquireCond.Add(string.Concat("ltrim(Convert(numeric(9,2), SUM(CASE WHEN ", f.DbName, " IN ('", string.Join("', '", f.FieldValue), "') THEN 1 ELSE 0 END)*100.0/Count(*))) + '%' AS '", f.FieldName, ":", string.Join(",", f.FieldValue).SubStr(60), "(%)'"));
      }
      else
      {
       inquireCond.Add(string.Concat("SUM(CASE WHEN ", f.DbName, " IN ('", string.Join("', '", f.FieldValue) , "') THEN 1 ELSE 0 END) AS '", f.FieldName, ":", string.Join(",", f.FieldValue).SubStr(60), "'"));
      }
     }
    });
   var whereCond = new List<string>();
   inquire.InquireFields.Where(f => f.FieldType == InquireHelper.FieldType.ConditionField).ToList()
    .ForEach(f =>
    {
     whereCond.Add(string.Concat(f.DbName, " IN ('", string.Join("','", f.FieldValue), "')"));
    });
   var groupCond = new List<string>();
   inquire.InquireFields.Where(f => f.FieldType == InquireHelper.FieldType.GroupField).ToList()
    .ForEach(f =>
    {
     groupCond.Add(f.DbName);
    });
   var orderbyCond = new List<string>();
   inquire.InquireFields.Where(f => f.FieldType == InquireHelper.FieldType.OrderByField).ToList()
    .ForEach(f =>
    {
     orderbyCond.Add(string.Concat(f.DbName, " ", f.OrderByAsc.GetValueOrDefault() ? "ASC" : "DESC"));
    });
   var sqlStr = string.Concat("SELECT ",
    string.Join(", ", inquireCond),
    " FROM GetStudentStatusByGxsj('", inquire.StatisticsDate , "')",
    whereCond.Any() ? " WHERE " : string.Empty,
    string.Join(" AND ", whereCond),
    groupCond.Any() ? " GROUP BY " : string.Empty,
    (inquire.ShowSubSummary || inquire.ShowSummary)
     ? string.Concat("rollup(", string.Join(", ", groupCond), ")")
     : string.Join(", ", groupCond),
    orderbyCond.Any() ? " ORDER BY " : string.Empty,
    string.Join(", ", orderbyCond));
   var dt = DBUtility.DbHelperSql.Query(sqlStr).Tables[0];
   if (!inquire.ShowSubSummary)
   {
    if (inquire.ShowSummary)
    {
     var col = inquire.InquireFields.Where(f => f.FieldType == InquireHelper.FieldType.GroupField).Count();
     for(int i = dt.Rows.Count - 2; i >=0 ; i -- ){
      if (dt.Rows[i][col - 1].ToString() == "")
      {
       dt.Rows.RemoveAt(i);
       //dt.Rows.Remove[dt.Rows[i]);
      }
     }
    }
   }
   else
   {
    var col = inquire.InquireFields.Where(f => f.FieldType == InquireHelper.FieldType.GroupField).Count();
    for (int i = 0; i < dt.Rows.Count - 1; i++)
    {
     for (int j = 1; j < col; j++)
     {
      if (dt.Rows[i][j].ToString() == "")
      {
       dt.Rows[i][j] = "  ";
       break;
      }
     }
    }
   }
   if (inquire.ShowSubSummary || inquire.ShowSummary)
   {
    dt.Rows[dt.Rows.Count - 1][0] = "  ";
   }
   return dt;
  }
  public static string SubStr(this string str, int maxLength)
  {
   if (str.Length > maxLength)
   {
    return str.Substring(0, maxLength - 1);
   }
   else
   {
    return str;
   }
  }
  public static string ToSerializableXML<T>(this T t)
  {
   XmlSerializer mySerializer = new XmlSerializer(typeof(T));
   StringWriter sw = new StringWriter();
   mySerializer.Serialize(sw, t);
   return sw.ToString();
  }
  public static T ToEntity<T>(this string xmlString)
  {
   var xs = new XmlSerializer(typeof(T));
   var srReader = new StringReader(xmlString);
   var steplist = (T)xs.Deserialize(srReader);
   return steplist;
  }
  public enum FieldType
  {
   DisplayField, GroupField, ConditionField, OrderByField
  }
  private static ConcurrentDictionary<InquireFieldBase, List<string>> _inquireItems = new ConcurrentDictionary<InquireFieldBase,List<string>>();
  public static List<string> GetInquireItemsByInquireType(this InquireFieldBase inquireField)
  {
   List<string> inquireItems;
   if (_inquireItems.TryGetValue(inquireField, out inquireItems))
   {
    return inquireItems;
   }
   switch (inquireField.GetType().Name)
   {
    case "XYMC_InquireField":
     inquireItems = new BLL.depacode().GetModelList("").OrderBy(d => d.xydm).Select(d => d.xymc).ToList();
     break;
    case "ZYMC_InquireField":
     inquireItems = new BLL.profcode().GetModelList("").OrderBy(d => d.xydm).ThenBy(d => d.zydm).Select(d => d.zymc).ToList();
     break;
    case "SZBJ_InquireField":
     inquireItems = DbHelperSql.Query("select distinct szbj from jbdate order by szbj").Tables[0].AsEnumerable().Select(b => b["szbj"].ToString()).ToList();
     break;
    case "FDY_InquireField":
     inquireItems = new BLL.DepaUser().GetModelList("").OrderBy(d => d.XYDM).ThenBy(y => y.YHXM).Select(d => d.YHXM).ToList();
     break;
    case "XL_InquireField":
     inquireItems = new[] { "  ", "  ", "   ", "  ", "  ", "  " }.ToList();
     break;
    case "SYDQ_InquireField":
     inquireItems = new[] { "  ", "  ", "  " }.ToList();
     break;
    case "SYSF_InquireField":
     inquireItems = DbHelperSql.Query("select [Name] from [Sydqdm] where RIGHT([code], 4) = '0000' order by code").Tables[0].AsEnumerable().Select(b => b["Name"].ToString()).ToList();
     break;
    case "DWDQ_InquireField":
     inquireItems = new[] { "  ", "  ", "  " }.ToList();
     break; 
    case "DWSF_InquireField":
     inquireItems = DbHelperSql.Query("select [Name] from [Sydqdm] where RIGHT([code], 4) = '0000' order by code").Tables[0].AsEnumerable().Select(b => b["Name"].ToString()).ToList();
     break;
    case "HYML_InquireField":
     inquireItems = DbHelperSql.Query("select distinct hyml from [hydygx]").Tables[0].AsEnumerable().Select(b => b["hyml"].ToString()).ToList();
     break;
    case "HYDL_InquireField":
     inquireItems = DbHelperSql.Query("select hydl from [hydygx] order by hydldm").Tables[0].AsEnumerable().Select(b => b["hydl"].ToString()).ToList();
     break;
    case "XBMC_InquireField":
     inquireItems = new[] { " ", " " }.ToList();
     break;
    case "MZMC_InquireField":
     inquireItems = DbHelperSql.Query("select nation from [mzdmb] where nation in (select nation from jbdate) order by mzdm").Tables[0].AsEnumerable().Select(b => b["nation"].ToString()).ToList();
     break;
    case "BYQX_InquireField":
     inquireItems = new BLL.Byqxdmb().GetModelList("").OrderBy(d => d.Byqxdm).Select(d => d.Byqxmc).ToList();
     break;
    case "KNSLB_InquireField":
     inquireItems = new[] { "    、       ", "       ", "       ", "  ", "       ", "    ", "    ", "    " }.ToList();
     break;
    case "ZYDKL_InquireField":
     inquireItems = new[] { "    ", "    ", "   ", "   " }.ToList();
     break;
    case "DWXZ_InquireField":
     inquireItems = new BLL.Dwxz().GetModelList("").OrderBy(d => d.dwxzdm).Select(d => d.dwxzmc).ToList();
     break;
    case "EJBYQXMC_InquireField":
     inquireItems = new BLL.EjByqxdmb().GetModelList("").OrderBy(d => d.Ejbyqxdm).Select(d => d.Ejbyqxmc).ToList();
     break;
   }
   if (inquireItems != null)
   {
    _inquireItems[inquireField] = inquireItems;
    return inquireItems;
   }
   return new List<string>();
  }
 }
 [Serializable]
 public class StatisticsInquire
 {
  public List<InquireFieldBase> InquireFields { get; set; } 
  [XmlAttribute]
  public bool ShowSummary { get; set; }
  [XmlAttribute]
  public bool ShowSubSummary { get; set; }
  [XmlAttribute]
  public string StatisticsDate { get; set; }
  [XmlAttribute]
  public HighChart.ChartType ChartType { get; set; }
 }
실제로 사용 중 에 도 매우 편리 하 다
향후 버 전 제작 이 필요 한 기능:
통계 필드 를 더욱 최적화 하여 여러 조건 을 조합 하여 같은 필드 를 선별 할 수 있 습 니 다.이것 은 비교적 간단 합 니 다.다음 종 류 를 확장 하고 UI 를 조정 하면 됩 니 다.

좋은 웹페이지 즐겨찾기