您的位置:首页 > 编程语言 > ASP

Asp.net管理信息系统中数据统计功能的实现

2017-07-11 21:37 399 查看
数据统计是每个系统中必备的功能,在给领导汇报统计数据,工作中需要的进展数据时非常有用。

在我看来,一个统计的模块应该实现以下功能:

能够将常用的查询的统计结果显示出来;

显示的结果可以是表格形式,也可以是图形形式,如果是图形的话能够以多种形式显示(柱状图、折线图、饼图、雷达图、堆叠柱状图等):

统计查询的结果,点击数字或者百分比能够显示详细的数据;

能够自由组合查询条件、筛选条件、分组条件、排序等;

统计结果最好有个实时预览;

查询统计能够保存,以便下次能直接调用并显示统计查询的结果;

对于保存后的查询统计,下次调用时也可以按照灵活的筛选手段对查询结果进行筛选;

界面需要做的简洁、直观,就算是不太懂电脑的操作员也能够方便使用;

对于一些复杂的查询,能够直接在后台写Sql或者调用Sp出数据

......

好了,以下是在实际环境中的实现和应用:
这是一个学生的就业系统,学生在不同的时期会对自己毕业去向进行登记,因此按照不同时间截点统计出来的数据是不一样的。数据表有100多个字段(并不是所有字段都需要统计)。

首先,我们在数据库中构建一个表值函数,能够按照不同的时间截点返回出数据,表也起到视图的作用,将参数表的值直接包含到返回结果中去。

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; }
}


View Code

实际在使用中,还是非常方便的

预计以后版本需要制作的功能:
对统计字段进行进一步优化,能够使用多个条件组合筛选同一个字段,这个比较简单,扩展下类并且UI调整下就可以了。

在这里把代码都分享给大家,希望和大家一起探讨。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐