之前有做个一个自定义报表的查询,这里使用的是一个动态的sql拼接,是前端选择了什么指标就查询什么信息!(这里的指标是多个表的字段,前端随便选择了这些指标,然后后端根据这些指标拼接sql,返回这些指标的数据)。

参数接收DTO

 /**
* 自定义报表
*/
public class DefinedReportFormDTO {
/**
* 指标id
*/
private List<Long> ids;
/**
* 开始时间
*/
@DateTimeFormat(pattern = "yyyy-MM")
private Date startTime;
/**
* 结束时间
*/
@DateTimeFormat(pattern = "yyyy-MM")
private Date endTime;
/**
* 频率
*/
private String timeStyle;
/**
* 机构id
*/
private List companyIds; private boolean avg =false; private String idsParam; private String companyIdsParam; public void setCompanyIdsParam(String companyIdsParam) {
this.companyIdsParam = companyIdsParam;
} public void setIdsParam(String idsParam) {
this.idsParam = idsParam;
} public String getCompanyIdsParam() {
return companyIdsParam;
} public String getIdsParam() {
return idsParam;
}
public boolean isAvg() {
return avg;
} public void setAvg(boolean avg) {
this.avg = avg;
} public Date getStartTime() {
return startTime;
} public void setStartTime(Date startTime) {
this.startTime = startTime;
} public Date getEndTime() {
return endTime;
} public void setEndTime(Date endTime) {
this.endTime = endTime;
} public String getTimeStyle() {
return timeStyle;
} public void setTimeStyle(String timeStyle) {
this.timeStyle = timeStyle;
} public List<Long> getIds() {
return ids;
} public void setIds(List<Long> ids) {
this.ids = ids;
} public List getCompanyIds() {
return companyIds;
} public void setCompanyIds(List companyIds) {
this.companyIds = companyIds;
} }

数据返回VO

 public class DefinedReportFormVO implements Serializable {
private String time;
private List<Map<String, Object>> arr = new ArrayList<>(); public String getTime() {
return time;
} public void setTime(String time) {
this.time = time;
} public List<Map<String, Object>> getArr() {
return arr;
} public void setArr(List<Map<String, Object>> arr) {
this.arr = arr;
} }

控制器Controller

   @GetMapping("/report/defindReport")
public JsonResponseExt defindReport(DefinedReportFormDTO definedReportFormDTO){ //测试数据 List list1 = new ArrayList<>();
list1.add("111");
definedReportFormDTO.setIds(list1);
definedReportFormDTO.setTimeStyle("month");
definedReportFormDTO.setAvg(true); Calendar instance = Calendar.getInstance();
instance.set(2018,1,11);
definedReportFormDTO.setStartTime(instance.getTime());
instance.setTime(new Date());
definedReportFormDTO.setEndTime(instance.getTime()); return JsonResponseExt.success(dataAcquisitionFileInfoService.defindQuery(definedReportFormDTO)); }

服务类Service

 public interface DataAcquisitionFileInfoService {

  List<DefinedReportFormVO> defindQuery(DefinedReportFormDTO parameter);

 }

实现类ServiceImpl

 @SuppressWarnings("unchecked")
@Override
public List<DefinedReportFormVO> defindQuery(DefinedReportFormDTO parameter) { /** * 定义五张表的查询字符串,年月,和机构id默认查询
*/
StringBuilder orgInformationCbrc = new StringBuilder("select reporting_year as reportingYear,reporting_month as reportingMonth, company_id ,");
StringBuilder orgBasicInformation = new StringBuilder("select reporting_year as reportingYear,reporting_month as reportingMonth, company_id,");
StringBuilder orgBusinessStructure = new StringBuilder("select reporting_year as reportingYear,reporting_month as reportingMonth, company_id,");
StringBuilder orgProfit = new StringBuilder("select reporting_year as reportingYear,reporting_month as reportingMonth, company_id,");
StringBuilder orgBalanceSheets = new StringBuilder("select reporting_year as reportingYear,reporting_month as reportingMonth, company_id,"); //定义机构的字符串
StringBuilder companyIds = new StringBuilder("");
//查询所有机构
List<Company> orgList = orgService.getOrgList(); //拼接所有机构的字符串(如果需要求平均数的话)
for (Company company : orgList) {
companyIds.append(company.getId()+",");
} companyIds.deleteCharAt(companyIds.length()-1);
//定义每个表的字符串判断
Map<String ,String> bool = new HashMap<>(); //指标名
List<String> fieldNames = new ArrayList();
//返回结果
List<Map<String,Object>> result = new ArrayList<>(); //指标名默认添加年月机构id
fieldNames.add("reportingYear");
fieldNames.add("reportingMonth");
fieldNames.add("companyId");
//定义指标id集合
List ids = parameter.getIds();
//循环所有的指标
for (Object id : ids) {
//如果指标为空
if (!"".equals(id) && id != null) {
//根据指标id查询指标
OrgStatisticalIndicators orgStatisticalIndicators = orgStatisticalIndicatorsRespository.findByIdAndAndDelFlag(Long.parseLong(id.toString()));
if(("year".equals(parameter.getTimeStyle()) && "0".equals(orgStatisticalIndicators.getYearQuery())) || ("month".equals(parameter.getTimeStyle()) && "0".equals(orgStatisticalIndicators.getMonthQuery()))){
/**
* 判断指标所在的表,然后为各自的表拼接上表的字段
*/
if ("org_information_cbrc".equals(orgStatisticalIndicators.getTableName())) {
orgInformationCbrc.append("ifnull("+orgStatisticalIndicators.getTableField()+",0) AS "+orgStatisticalIndicators.getField()+" ,");
//
if (bool.get("org_information_cbrc") == null) {
bool.put("org_information_cbrc", orgStatisticalIndicators.getTableField());
}
//如果其他表不存在这个属性则为其他表拼接null
orgBasicInformation.append("null as " + orgStatisticalIndicators.getField() + ",");
orgBalanceSheets.append("null as " + orgStatisticalIndicators.getField() + ",");
orgBusinessStructure.append("null as " + orgStatisticalIndicators.getField() + ",");
orgProfit.append("null as " + orgStatisticalIndicators.getField() + ","); //行业平均
if (parameter.isAvg()) {
if("year".equals(parameter.getTimeStyle())){
orgInformationCbrc.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear AND reporting_month = '12' ) AS "+orgStatisticalIndicators.getField()+"Avg,");
}else{
orgInformationCbrc.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,");
} orgBalanceSheets.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); orgBasicInformation.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); orgBusinessStructure.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); orgProfit.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); } } else if ("org_basic_information".equals(orgStatisticalIndicators.getTableName())) {
if (bool.get("org_basic_information") == null) {
bool.put("org_basic_information", orgStatisticalIndicators.getTableField());
} orgBasicInformation.append("ifnull("+orgStatisticalIndicators.getTableField()+",0) AS "+orgStatisticalIndicators.getField()+" ,");
orgInformationCbrc.append("null as " + orgStatisticalIndicators.getField() + ",");
orgBalanceSheets.append("null as " + orgStatisticalIndicators.getField() + ",");
orgBusinessStructure.append("null as " + orgStatisticalIndicators.getField() + ",");
orgProfit.append("null as " + orgStatisticalIndicators.getField() + ","); //行业平均
if (parameter.isAvg()) {
if("year".equals(parameter.getTimeStyle())){
orgBasicInformation.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear AND reporting_month = '12' ) AS "+orgStatisticalIndicators.getField()+"Avg,");
}else{
orgBasicInformation.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,");
} orgProfit.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,");
orgInformationCbrc.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,");
orgBalanceSheets.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,");
orgBusinessStructure.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); } } else if ("org_business_structure".equals(orgStatisticalIndicators.getTableName())) {
orgBusinessStructure.append("ifnull("+orgStatisticalIndicators.getTableField()+",0) AS "+orgStatisticalIndicators.getField()+" ,");
if (bool.get("org_business_structure") == null) {
bool.put("org_business_structure", orgStatisticalIndicators.getTableField());
} orgBasicInformation.append("null as " + orgStatisticalIndicators.getField() + ",");
orgInformationCbrc.append("null as " + orgStatisticalIndicators.getField() + ",");
orgBalanceSheets.append("null as " + orgStatisticalIndicators.getField() + ",");
orgProfit.append("null as " + orgStatisticalIndicators.getField() + ","); //行业平均
if (parameter.isAvg()) {
if("year".equals(parameter.getTimeStyle())){
orgBusinessStructure.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear AND reporting_month = '12' ) AS "+orgStatisticalIndicators.getField()+"Avg,");
}else{
orgBusinessStructure.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,");
} orgProfit.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,");
orgInformationCbrc.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,");
orgBalanceSheets.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,");
orgBasicInformation.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); }
} else if ("org_profit".equals(orgStatisticalIndicators.getTableName())) {
orgProfit.append("ifnull("+orgStatisticalIndicators.getTableField()+",0) AS "+orgStatisticalIndicators.getField()+" ,");
if (bool.get("org_profit") == null) {
bool.put("org_profit", orgStatisticalIndicators.getTableField());
} orgBasicInformation.append("null as " + orgStatisticalIndicators.getField() + ",");
orgInformationCbrc.append("null as " + orgStatisticalIndicators.getField() + ",");
orgBalanceSheets.append("null as " + orgStatisticalIndicators.getField() + ",");
orgBusinessStructure.append("null as " + orgStatisticalIndicators.getField() + ","); //行业平均
if (parameter.isAvg()) {
if("year".equals(parameter.getTimeStyle())){
orgProfit.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear AND reporting_month = '12' ) AS "+orgStatisticalIndicators.getField()+"Avg,");
}else{
orgProfit.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,");
} orgBasicInformation.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,");
orgInformationCbrc.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,");
orgBalanceSheets.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,");
orgBusinessStructure.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); } } else if ("org_balance_sheets".equals(orgStatisticalIndicators.getTableName())) {
orgBalanceSheets.append("ifnull("+orgStatisticalIndicators.getTableField()+",0) AS "+orgStatisticalIndicators.getField()+" ,");
if (bool.get("org_balance_sheets") == null) {
bool.put("org_balance_sheets", orgStatisticalIndicators.getTableField());
} orgBasicInformation.append("null as " + orgStatisticalIndicators.getField() + ",");
orgInformationCbrc.append("null as " + orgStatisticalIndicators.getField() + ",");
orgBusinessStructure.append("null as " + orgStatisticalIndicators.getField() + ",");
orgProfit.append("null as " + orgStatisticalIndicators.getField() + ","); //行业平均
if (parameter.isAvg()) {
if("year".equals(parameter.getTimeStyle())){
orgBalanceSheets.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear AND reporting_month = '12' ) AS "+orgStatisticalIndicators.getField()+"Avg,");
}else{
orgBalanceSheets.append("(SELECT avg("+orgStatisticalIndicators.getTableField()+") FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,");
} orgProfit.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,");
orgInformationCbrc.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,");
orgBalanceSheets.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,");
orgBusinessStructure.append("(SELECT avg(null) FROM "+orgStatisticalIndicators.getTableName()+" where reporting_year = reportingYear and reporting_month = reportingMonth) AS "+orgStatisticalIndicators.getField()+"Avg,"); }
}
if (parameter.isAvg()==true) {
fieldNames.add(orgStatisticalIndicators.getField());
fieldNames.add(orgStatisticalIndicators.getField()+"Avg");
} else {
fieldNames.add(orgStatisticalIndicators.getField());
} } }
} //拼接where条件
StringBuilder whereSql = new StringBuilder(" WHERE 1 = 1"); if("year".equals(parameter.getTimeStyle())){
whereSql.append(" AND reporting_year >= :startYear and reporting_year <= :endYear AND reporting_month = '12' ");
}else{
whereSql.append(" and CONCAT(reporting_year , '-' ,Right(100+CAST(reporting_month as SIGNED),2) )>= :startYear and CONCAT(reporting_year , '-' ,Right(100+CAST(reporting_month as SIGNED),2) ) <= :endYear");
} //获取所有机构id
List parameterCompanyIds = parameter.getCompanyIds();
//如果机构id不为空
if (parameterCompanyIds.size()>0) {
whereSql.append(" AND company_id in ( "); for (int i = 0; i < parameterCompanyIds.size(); i++) {
whereSql.append(":s"+i+" ,");
} whereSql.deleteCharAt(whereSql.length()-1);
whereSql.append(" )");
} //定义Query
Query orgBalanceSheetsQuery = null; //拼接五张表和条件
orgBalanceSheets.deleteCharAt(orgBalanceSheets.length()-1);
orgBalanceSheets.append(" from org_balance_sheets ");
orgBalanceSheets.append(whereSql); orgBasicInformation.deleteCharAt(orgBasicInformation.length()-1);
orgBasicInformation.append(" from org_basic_information ");
orgBasicInformation.append(whereSql); orgBusinessStructure.deleteCharAt(orgBusinessStructure.length()-1);
orgBusinessStructure.append(" from org_business_structure ");
orgBusinessStructure.append(whereSql); orgInformationCbrc.deleteCharAt(orgInformationCbrc.length()-1);
orgInformationCbrc.append(" from org_information_cbrc ");
orgInformationCbrc.append(whereSql); orgProfit.deleteCharAt(orgProfit.length()-1);
orgProfit.append(" from org_profit ");
orgProfit.append(whereSql); //关联五张表
orgBalanceSheets.append(" UNION ");
orgBalanceSheets.append(orgBasicInformation.toString()); orgBalanceSheets.append(" UNION ");
orgBalanceSheets.append(orgBusinessStructure.toString()); orgBalanceSheets.append(" UNION ");
orgBalanceSheets.append(orgInformationCbrc.toString()); orgBalanceSheets.append(" UNION ");
orgBalanceSheets.append(orgProfit.toString()); System.out.println(">>"+orgBalanceSheets.toString()); //创建本地sql查询实例
orgBalanceSheetsQuery = entityManager.createNativeQuery(orgBalanceSheets.toString()); //如果时间为空那就获取现在的时间
if(parameter.getEndTime() == null){
parameter.setEndTime(new Date());
}
if(parameter.getStartTime() == null){
parameter.setStartTime(new Date());
} if("year".equals(parameter.getTimeStyle())){ orgBalanceSheetsQuery.setParameter("startYear", com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getStartTime(),"yyyy")); orgBalanceSheetsQuery.setParameter("endYear", com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getEndTime(),"yyyy"));
}else if("month".equals(parameter.getTimeStyle())){ orgBalanceSheetsQuery.setParameter("startYear", com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getStartTime(),"yyyy-MM")); orgBalanceSheetsQuery.setParameter("endYear", com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getEndTime(),"yyyy-MM")); } if (parameterCompanyIds.size()>0) { for (int i = 0; i < parameterCompanyIds.size(); i++) {
orgBalanceSheetsQuery.setParameter("s"+i, parameterCompanyIds.get(i));
}
} //获取数据
List resultList = orgBalanceSheetsQuery.getResultList(); System.out.println("resultList==="+resultList); //给数据设置属性
for (int i = 0; i < resultList.size(); i++) {
Object o = resultList.get(i);
Object[] cells = (Object[]) o;
Map<String,Object> map = new HashMap<>();
if(cells.length == 3){
continue;
}
for (int j = 0; j<cells.length; j++) { if (cells[j] != null && !"".equals(cells[j].toString())) {
map.put((String) fieldNames.get(j),cells[j]);
}else{
setField(resultList,fieldNames,map,i,j);
} }
result.add(map);
} System.out.println("result == "+result); List<DefinedReportFormVO> definedReportFormVOList = new ArrayList<>();
Map<String,List> stringListMap = new HashMap<>(); //定义返回的格式
for (Map<String, Object> map : result) {
String reportingYear = (String) map.get("reportingYear");
String reportingMonth = (String) map.get("reportingMonth");
String reportingDate = reportingYear+"-"+reportingMonth;
//如果时间类型是年
if ("year".equals(parameter.getTimeStyle())) {
List list = stringListMap.get(reportingYear);
if (list != null) {
list.add(map);
stringListMap.put(reportingYear,list);
}else{
List inner =new ArrayList();
inner.add(map);
stringListMap.put(reportingYear,inner);
}
}else{//如果为月 List list = stringListMap.get(reportingDate);
if (list != null) {
list.add(map);
stringListMap.put(reportingDate,list);
}else{
List inner =new ArrayList();
inner.add(map);
stringListMap.put(reportingDate,inner);
}
} } System.out.println("stringListMap == "+stringListMap); for (Map.Entry<String,List> entry : stringListMap.entrySet()) {
DefinedReportFormVO formVO = new DefinedReportFormVO();
formVO.setTime(entry.getKey()); if(parameter.isAvg()==true){
formVO.setArr(setAvg(entry.getValue(),fieldNames));
}else{
formVO.setArr(entry.getValue());
} definedReportFormVOList.add(formVO); } return definedReportFormVOList;
}

指标实体

 /**
* 统计指标
*/
@Entity
@Table(name = "org_statistical_indicators", catalog = "zhsupervision")
public class OrgStatisticalIndicators {
@Id
@GeneratedValue
private Long id;
/**
* 前端显示名
*/
private String name;
/**
* 表属性
*/
private String tableField;
/**
* 表名称
*/
private String tableName;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
/**
* 删除标识
*/
private String delFlag;
//父节点
private Long pId;
//属性
private String field;
//该指标查询月的时候是否查询
private String monthQuery;
//该指标查询年的时候是否查询
private String yearQuery; public String getMonthQuery() {
return monthQuery;
} public void setMonthQuery(String monthQuery) {
this.monthQuery = monthQuery;
} public String getYearQuery() {
return yearQuery;
} public void setYearQuery(String yearQuery) {
this.yearQuery = yearQuery;
} public String getField() {
return field;
} public void setField(String field) {
this.field = field;
} public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public Long getpId() {
return pId;
} public void setpId(Long pId) {
this.pId = pId;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getTableField() {
return tableField;
} public void setTableField(String tableField) {
this.tableField = tableField;
} public String getTableName() {
return tableName;
} public void setTableName(String tableName) {
this.tableName = tableName;
} public Date getCreateTime() {
return createTime;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
} public Date getUpdateTime() {
return updateTime;
} public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
} public String getDelFlag() {
return delFlag;
} public void setDelFlag(String delFlag) {
this.delFlag = delFlag;
} }

指标Service

 /**
* 统计指标服务类
*/
public interface OrgStatisticalIndicatorsService {
/**
* 根据id获取
* @param id
* @return
*/
OrgStatisticalIndicators findOrgStatisticalIndicatorsById(Long id); /**
* 根据表名查询
*/
List<OrgStatisticalIndicators> findOrgStatisticalIndicatorsByTableName(String name); }

指标serviceImpl

 @Service
public class OrgStatisticalIndicatorsServiceImpl extends BaseServiceImpl<OrgStatisticalIndicators, String> implements OrgStatisticalIndicatorsService { @Autowired
private OrgStatisticalIndicatorsRespository respository; @Override
public OrgStatisticalIndicators findOrgStatisticalIndicatorsById(Long id) {
return respository.findByIdAndAndDelFlag(id);
} @Override
public List<OrgStatisticalIndicators> findOrgStatisticalIndicatorsByTableName(String name) {
return respository.findOrgStatisticalIndicatorsByTableName(name);
}
}

指标repository

 public interface OrgStatisticalIndicatorsRespository extends JpaSpecificationExecutor {

         @Query(value = "select * from org_statistical_indicators WHERE  ID=?1 and del_flag = '0'",nativeQuery = true)
OrgStatisticalIndicators findByIdAndAndDelFlag(Long id); @Query(value = "select * from org_statistical_indicators WHERE del_flag = '0' and NAME =?1",nativeQuery = true)
OrgStatisticalIndicators findOrgStatisticalIndicatorsByName(String name); }

这个repository要继承 extends JpaRepository<T, ID> 才可以,写漏了。

上面使用了union 进行表之间的关联查询,关联的表有点多,所以代码有些长,同时因为表多,指标(表的属性)有500多个,无法确定查询的返回实体,所以只能自己根据数据的返回给数据绑定属性。

  写完之后我发现语句太长并且嵌套了子查询后执行的时间也变长了,有时候还会卡,所以我优化了一下,指标查询指标,统计查询统计这样的执行时间就变短了,而且后来需求有所改变,有区分年查询和月查询。以下是我对实现类和指标实体的修改。

指标实体:

 /**
* 统计指标
*/
@Entity
@Table(name = "org_statistical_indicators", catalog = "zhsupervision")
public class OrgStatisticalIndicators {
@Id
@GeneratedValue
private Long id;
/**
* 前端显示名
*/
private String name;
/**
* 表属性
*/
private String tableField;
/**
* 表名称
*/
private String tableName;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
/**
* 删除标识
*/
private String delFlag; private Long pId; private String field; private String monthQuery; private String yearQuery; private String isQuery; private String avgQuery; public String getAvgQuery() {
return avgQuery;
} public void setAvgQuery(String avgQuery) {
this.avgQuery = avgQuery;
} public String getIsQuery() {
return isQuery;
} public void setIsQuery(String isQuery) {
this.isQuery = isQuery;
} public String getMonthQuery() {
return monthQuery;
} public void setMonthQuery(String monthQuery) {
this.monthQuery = monthQuery;
} public String getYearQuery() {
return yearQuery;
} public void setYearQuery(String yearQuery) {
this.yearQuery = yearQuery;
} public String getField() {
return field;
} public void setField(String field) {
this.field = field;
} public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public Long getpId() {
return pId;
} public void setpId(Long pId) {
this.pId = pId;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getTableField() {
return tableField;
} public void setTableField(String tableField) {
this.tableField = tableField;
} public String getTableName() {
return tableName;
} public void setTableName(String tableName) {
this.tableName = tableName;
} public Date getCreateTime() {
return createTime;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
} public Date getUpdateTime() {
return updateTime;
} public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
} public String getDelFlag() {
return delFlag;
} public void setDelFlag(String delFlag) {
this.delFlag = delFlag;
}
}

实现类Impl:

     @SuppressWarnings("unchecked")
@Override
public List<DefinedReportFormVO> defindQuery(DefinedReportFormDTO parameter) { /**
* 定义五张表的查询字符串,年月,和机构id默认查询
*/
StringBuilder orgInformationCbrc = new StringBuilder("select ID as cbrcId, reporting_year as reportingYear,reporting_month as reportingMonth, company_id as companyId,");
StringBuilder orgBasicInformation = new StringBuilder("select ID as basicId ,reporting_year as reportingYear,reporting_month as reportingMonth, company_id as companyId,");
StringBuilder orgBusinessStructure = new StringBuilder("select ID as businessId ,reporting_year as reportingYear,reporting_month as reportingMonth, company_id as companyId,");
StringBuilder orgProfit = new StringBuilder("select ID as profitId ,reporting_year as reportingYear,reporting_month as reportingMonth, company_id as companyId ,");
StringBuilder orgBalanceSheets = new StringBuilder("select ID as balanceId, reporting_year as reportingYear,reporting_month as reportingMonth, company_id as companyId ,");
/**
* 平均数sql
*/
StringBuilder orgInformationCbrcAvg = new StringBuilder("select reporting_year ,reporting_month , ");
StringBuilder orgBasicInformationAvg = new StringBuilder("select reporting_year ,reporting_month , ");
StringBuilder orgBusinessStructureAvg = new StringBuilder("select reporting_year ,reporting_month , ");
StringBuilder orgProfitAvg = new StringBuilder("select reporting_year ,reporting_month , ");
StringBuilder orgBalanceSheetsAvg = new StringBuilder("select reporting_year ,reporting_month , "); //指标名
List<String> fieldNames = new ArrayList(); //指标名默认添加年月机构id
fieldNames.add("id");
fieldNames.add("reportingYear");
fieldNames.add("reportingMonth");
fieldNames.add("companyId"); //记录是哪一个表的平均数
List<String> orgInformationCbrcAvgField = new ArrayList<>();
List<String> orgBasicInformationAvgField = new ArrayList<>();
List<String> orgBusinessStructureAvgField = new ArrayList<>();
List<String> orgProfitAvgField = new ArrayList<>();
List<String> orgBalanceSheetsAvgField = new ArrayList<>(); orgInformationCbrcAvgField.add("reportingYear");
orgInformationCbrcAvgField.add("reportingMonth"); orgBasicInformationAvgField.add("reportingYear");
orgBasicInformationAvgField.add("reportingMonth"); orgBusinessStructureAvgField.add("reportingYear");
orgBusinessStructureAvgField.add("reportingMonth"); orgProfitAvgField.add("reportingYear");
orgProfitAvgField.add("reportingMonth"); orgBalanceSheetsAvgField.add("reportingYear");
orgBalanceSheetsAvgField.add("reportingMonth"); //返回前端的结果集
List<DefinedReportFormVO> definedReportFormVOList = new ArrayList<>();
//指标结果集
Map<String,List<Map<String,Object>>> stringListMap = new HashMap<String,List<Map<String,Object>>>();
//指标Query
Query orgBalanceSheetsQuery = null; //平均数结果集
Map<String,List<Map<String,Object>>> avgListMap = new HashMap<String,List<Map<String,Object>>>(); //获取机构id
List parameterCompanyIds = parameter.getCompanyIds(); List<OrgStatisticalIndicators> orgStatisticalIndicatorsByIds = orgStatisticalIndicatorsRespository.findOrgStatisticalIndicatorsByIds(parameter.getIds()); for (OrgStatisticalIndicators orgStatisticalIndicators : orgStatisticalIndicatorsByIds) {
String query = "";
String field = orgStatisticalIndicators.getField();
String isQuery = orgStatisticalIndicators.getIsQuery();
String isAvgQuery = orgStatisticalIndicators.getAvgQuery();
String tableName = orgStatisticalIndicators.getTableName();
/**
* 1.前端显示后端不查询
* 0.前端显示后端也查询
*/
if("1".equals(isQuery)){
continue;
} /**
* year.按照年份查询
* month.按照月查询
*/
if("year".equals(parameter.getTimeStyle())){
query = orgStatisticalIndicators.getYearQuery();
}else{
query = orgStatisticalIndicators.getMonthQuery();
}
//如果结果为空跳过本次循环
if(query == null || "".equals(query)){
continue;
} /**
* 判断指标所在的表,然后为各自的表拼接上表的字段
*/
if ("org_information_cbrc".equals(tableName)) { if(parameterCompanyIds.size()>0){
orgInformationCbrc.append(query+" ,"); //如果其他表不存在这个属性则为其他表拼接null
orgBasicInformation.append("null as "+field+",");
orgBalanceSheets.append("null as "+field+",");
orgBusinessStructure.append("null as "+field+",");
orgProfit.append("null as "+field+",");
} //行业平均
if (parameter.isAvg() ==true && !"1".equals(isAvgQuery)) {
orgInformationCbrcAvg.append(" avg("+query+"),");
orgInformationCbrcAvgField.add(field); }
} else if ("org_basic_information".equals(tableName)) {
if(parameterCompanyIds.size()>0){
orgBasicInformation.append(query+" ,"); orgInformationCbrc.append("null as "+field+",");
orgBalanceSheets.append("null as "+field+",");
orgBusinessStructure.append("null as "+field+",");
orgProfit.append("null as "+field+",");
} //行业平均
if (parameter.isAvg() && !"1".equals(isAvgQuery)) {
orgBasicInformationAvg.append("avg("+query+"),");
orgBasicInformationAvgField.add(field); } } else if ("org_business_structure".equals(tableName)) {
if(parameterCompanyIds.size()>0){
orgBusinessStructure.append(query+" ,"); orgBasicInformation.append("null as "+field+",");
orgInformationCbrc.append("null as "+field+",");
orgBalanceSheets.append("null as "+field+",");
orgProfit.append("null as "+field+",");
} //行业平均
if (parameter.isAvg() && !"1".equals(isAvgQuery)) {
orgBusinessStructureAvg.append("avg("+query+"),");
orgBusinessStructureAvgField.add(field);
}
} else if ("org_profit".equals(tableName)) { if(parameterCompanyIds.size()>0){
orgProfit.append(query+" AS "+field+" ,");
orgBasicInformation.append("null as "+field+",");
orgInformationCbrc.append("null as "+field+",");
orgBalanceSheets.append("null as "+field+",");
orgBusinessStructure.append("null as "+field+",");
} //行业平均
if (parameter.isAvg() && !"1".equals(isAvgQuery)) {
orgProfitAvg.append("avg("+query+"),");
orgProfitAvgField.add(field);
}
} else if ("org_balance_sheets".equals(tableName)) {
if(parameterCompanyIds.size()>0){
orgBalanceSheets.append(query+" ,"); orgBasicInformation.append("null as "+field+",");
orgInformationCbrc.append("null as "+field+",");
orgBusinessStructure.append("null as "+field+",");
orgProfit.append("null as "+field+",");
} //行业平均
if (parameter.isAvg() == true && !"1".equals(isAvgQuery)) { orgBalanceSheetsAvg.append("avg("+query+"),");
orgBalanceSheetsAvgField.add(field); }
}else if("org_basic_info_list".equals(tableName)){//因为这几个字段关联的是其他表所以使用子查询 if(orgStatisticalIndicators.getName().startsWith("银行")){
if(parameterCompanyIds.size()>0){
orgBasicInformation.append("(SELECT "+query+" FROM "+tableName+" where org_basic_id = ID and type ='1' limit 1) ,"); orgInformationCbrc.append("null as "+field+",");
orgBalanceSheets.append("null as "+field+",");
orgBusinessStructure.append("null as "+field+",");
orgProfit.append("null as "+field+",");
} if(parameter.isAvg() == true && !"1".equals(isAvgQuery)){
orgBasicInformationAvg.append("(SELECT avg("+query+") FROM "+tableName+" where org_basic_id = ID and type ='1' limit 1) ,");
} }else if(orgStatisticalIndicators.getName().startsWith("资本")){
if(parameterCompanyIds.size()>0){
orgBasicInformation.append("(SELECT "+query+" FROM "+tableName+" where org_basic_id = ID and type ='0'limit 1) ,"); orgInformationCbrc.append("null as "+field+"1,");
orgBalanceSheets.append("null as "+field+"1,");
orgBusinessStructure.append("null as "+field+"1,");
orgProfit.append("null as "+field+"1,");
}
if(parameter.isAvg() == true && !"1".equals(isAvgQuery)){
orgBasicInformationAvg.append("(SELECT avg("+query+") FROM "+tableName+" where org_basic_id = ID and type ='0' limit 1) ,");
}
} if (parameter.isAvg()==true && !"1".equals(isAvgQuery)) {
orgBasicInformationAvgField.add(field);
} }
if (!"1".equals(isQuery)) {
if(parameterCompanyIds.size()>0){
fieldNames.add(field);
}
} } //拼接where条件
StringBuilder whereSql = new StringBuilder(" WHERE 1 = 1"); if("year".equals(parameter.getTimeStyle())){
whereSql.append(" AND reporting_year >= :startYear and reporting_year <= :endYear AND reporting_month = '12' ");
}else{
whereSql.append(" and CONCAT(reporting_year , '-' ,Right(100+CAST(reporting_month as SIGNED),2) )>= :startYear and CONCAT(reporting_year , '-' ,Right(100+CAST(reporting_month as SIGNED),2) ) <= :endYear");
} //如果机构id不为空
if (parameterCompanyIds.size()>0) {
whereSql.append(" AND company_id in ( "); for (int i = 0; i < parameterCompanyIds.size(); i++) {
whereSql.append(":s"+i+" ,");
} whereSql.deleteCharAt(whereSql.length()-1);
whereSql.append(" )");
} //拼接五张表和条件
orgBalanceSheets.deleteCharAt(orgBalanceSheets.length()-1);
orgBalanceSheets.append(" from org_balance_sheets ");
orgBalanceSheets.append(whereSql); orgBasicInformation.deleteCharAt(orgBasicInformation.length()-1);
orgBasicInformation.append(" from org_basic_information ");
orgBasicInformation.append(whereSql); orgBusinessStructure.deleteCharAt(orgBusinessStructure.length()-1);
orgBusinessStructure.append(" from org_business_structure ");
orgBusinessStructure.append(whereSql); orgInformationCbrc.deleteCharAt(orgInformationCbrc.length()-1);
orgInformationCbrc.append(" from org_information_cbrc ");
orgInformationCbrc.append(whereSql); orgProfit.deleteCharAt(orgProfit.length()-1);
orgProfit.append(" from org_profit ");
orgProfit.append(whereSql); //关联五张表
orgBalanceSheets.append(" UNION ");
orgBalanceSheets.append(orgBasicInformation.toString()); orgBalanceSheets.append(" UNION ");
orgBalanceSheets.append(orgBusinessStructure.toString()); orgBalanceSheets.append(" UNION ");
orgBalanceSheets.append(orgInformationCbrc.toString()); orgBalanceSheets.append(" UNION ");
orgBalanceSheets.append(orgProfit.toString()); //如果有选机构
if(parameterCompanyIds.size() > 0){
//创建本地sql查询实例
orgBalanceSheetsQuery = entityManager.createNativeQuery(orgBalanceSheets.toString()); //如果时间为空那就获取现在的时间
if(parameter.getEndTime() == null){
parameter.setEndTime(new Date());
}
if(parameter.getStartTime() == null){
parameter.setStartTime(new Date());
} if("year".equals(parameter.getTimeStyle())){ orgBalanceSheetsQuery.setParameter("startYear", com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getStartTime(),"yyyy")); orgBalanceSheetsQuery.setParameter("endYear", com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getEndTime(),"yyyy"));
}else if("month".equals(parameter.getTimeStyle())){ orgBalanceSheetsQuery.setParameter("startYear", com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getStartTime(),"yyyy-MM")); orgBalanceSheetsQuery.setParameter("endYear", com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getEndTime(),"yyyy-MM")); } if (parameterCompanyIds.size()>0) { for (int i = 0; i < parameterCompanyIds.size(); i++) {
orgBalanceSheetsQuery.setParameter("s"+i, parameterCompanyIds.get(i));
}
} //返回结果
List<Map<String,Object>> result = new ArrayList<>(); //获取数据
List resultList = orgBalanceSheetsQuery.getResultList(); dataEncapsulation(resultList, fieldNames, result); //
for (Map<String, Object> map : result) {
String reportingYear = (String) map.get("reportingYear");
String reportingMonth = (String) map.get("reportingMonth");
String reportingDate = reportingYear+"-"+reportingMonth;
//如果时间类型是年
if ("year".equals(parameter.getTimeStyle())) {
List list = stringListMap.get(reportingYear);
if (list != null) {
list.add(map);
stringListMap.put(reportingYear,list);
}else{
List inner =new ArrayList();
inner.add(map);
stringListMap.put(reportingYear,inner);
}
}else{//如果为月 List list = stringListMap.get(reportingDate);
if (list != null) {
list.add(map);
stringListMap.put(reportingDate,list);
}else{
List inner =new ArrayList();
inner.add(map);
stringListMap.put(reportingDate,inner);
}
} } } /**
* 平均数
*/
if (parameter.isAvg() == true) { //定义Query
Query avgQuerey = null; String where = "";
/**
* 年月查询sql
* 1.年查询的是本年的第12月的数据
* 2.月查询是查询开始到结束的数据
*/
if("month".equals(parameter.getTimeStyle())){
where = " where CONCAT( reporting_year,'-',RIGHT (100 + CAST(reporting_month AS SIGNED),2)) >= :startTime AND CONCAT( reporting_year,'-',RIGHT (100 + CAST(reporting_month AS SIGNED),2)) <= :endTime GROUP BY reporting_year,reporting_month ";
}else{
where = " where reporting_year >= :startTime AND reporting_year<= :endTime AND reporting_month = '12' GROUP BY reporting_year,reporting_month ";
} String startTime = "";
String endTime = "";
/**
* 年查询和月查询所给时间赋的值是不一样的
*/
if("year".equals(parameter.getTimeStyle())){
startTime = com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getStartTime(),"yyyy");
endTime = com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getEndTime(),"yyyy");
}else{
startTime = com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getStartTime(),"yyyy-MM");
endTime = com.honebay.spv.core.utils.DateUtil.formatDate(parameter.getEndTime(),"yyyy-MM");
} //如果有这个集合添加的属性超过2个(年月默认添加了)
if(orgBalanceSheetsAvgField.size()>2){
orgBalanceSheetsAvg.deleteCharAt(orgBalanceSheetsAvg.length()-1);
orgBalanceSheetsAvg.append(" from org_balance_sheets ");
orgBalanceSheetsAvg.append(where);
avgSetValue(avgQuerey,orgBalanceSheetsAvg,startTime,endTime,orgBalanceSheetsAvgField,parameter.getTimeStyle(),avgListMap);
} if(orgProfitAvgField.size()>2){
orgProfitAvg.deleteCharAt(orgProfitAvg.length()-1);
orgProfitAvg.append(" from org_profit ");
orgProfitAvg.append(where);
avgSetValue(avgQuerey,orgProfitAvg,startTime,endTime,orgProfitAvgField,parameter.getTimeStyle(),avgListMap);
} if(orgBasicInformationAvgField.size() > 2){
orgBasicInformationAvg.deleteCharAt(orgBasicInformationAvg.length()-1);
orgBasicInformationAvg.append(" from org_basic_information ");
orgBasicInformationAvg.append(where);
avgSetValue(avgQuerey,orgBasicInformationAvg,startTime,endTime,orgBasicInformationAvgField,parameter.getTimeStyle(),avgListMap);
} if(orgBusinessStructureAvgField.size() > 2){
orgBusinessStructureAvg.deleteCharAt(orgBusinessStructureAvg.length()-1);
orgBusinessStructureAvg.append(" from org_business_structure ");
orgBusinessStructureAvg.append(where);
avgSetValue(avgQuerey,orgBusinessStructureAvg,startTime,endTime,orgBusinessStructureAvgField,parameter.getTimeStyle(),avgListMap);
} if(orgInformationCbrcAvgField.size() > 2){
orgInformationCbrcAvg.deleteCharAt(orgInformationCbrcAvg.length()-1);
orgInformationCbrcAvg.append(" from org_information_cbrc ");
orgInformationCbrcAvg.append(where);
avgSetValue(avgQuerey,orgInformationCbrcAvg,startTime,endTime,orgInformationCbrcAvgField,parameter.getTimeStyle(),avgListMap);
} }
/**
* 1.如果指标查询的集合为空将平均数的集合赋值给它
* 2.如果都有数据就将他们的相同时间段的添加在一起
* 3.如果平均数为空就不用操作直接返回指标查询
*/ if(stringListMap.size() == 0){
stringListMap.putAll(avgListMap);
}else if(stringListMap.size() > 0 && avgListMap.size() > 0){ for (Map.Entry<String, List<Map<String, Object>>> entry : stringListMap.entrySet()) {
System.out.println(entry.getValue()+"=="+entry.getKey());
List<Map<String, Object>> maps = avgListMap.get(entry.getKey());
if(maps != null){
List<Map<String, Object>> mapList = stringListMap.get(entry.getKey());
for (Map<String, Object> map : maps) {
mapList.add(map);
} }
} } //绑定Vo对象
for (Map.Entry<String, List<Map<String, Object>>> entry : stringListMap.entrySet()) {
DefinedReportFormVO formVO = new DefinedReportFormVO();
formVO.setTime(entry.getKey());
formVO.setArr(entry.getValue());
definedReportFormVOList.add(formVO);
} return definedReportFormVOList;
} /**
* 平均数的sql执行、参数设置和结果格式化
* @param avgQuerey Query对象
* @param orgBalanceSheetsAvg sql
* @param startTime 开始时间
* @param endTime 结束时间
* @param orgBalanceSheetsField 属性集合
* @param timeStyle 时间类型
* @param stringListMap 最终结果集
*/
public void avgSetValue(Query avgQuerey,StringBuilder orgBalanceSheetsAvg, String startTime,String endTime,List<String> orgBalanceSheetsField,String timeStyle,Map<String,List<Map<String,Object>>> stringListMap) {
//创建本地sql查询实例
avgQuerey = entityManager.createNativeQuery(orgBalanceSheetsAvg.toString()); avgQuerey.setParameter("startTime", startTime); avgQuerey.setParameter("endTime", endTime); List queryResultList = avgQuerey.getResultList(); avgDataEncapsulation(queryResultList, orgBalanceSheetsField,timeStyle,stringListMap); } /**
*
* @param resultList 执行sql得到的结果集
* @param field 属性集合
* @param result 最终得到的数据
*/
public void dataEncapsulation(List resultList,List field , List<Map<String,Object>> result){
//给数据设置属性
for (int i = 0; i < resultList.size(); i++) {
Object o = resultList.get(i);
Object[] cells = (Object[]) o;
Map<String,Object> map = new HashMap<>();
if(cells.length <= 4){
continue;
}
for (int j = 0; j<cells.length; j++) {
if (cells[j] != null && !"".equals(cells[j].toString())) {
map.put((String) field.get(j),cells[j]);
}else{
setField(resultList,field,map,i,j);
}
} result.add(map);
} } /**
* 平均数
* @param resultList 执行sql得到的结果集
* @param fieldNames 属性集合
* @param timeStyle 时间类型
* @param stringListMap 最终得到的结果集
*/
public void avgDataEncapsulation(List resultList,List fieldNames ,String timeStyle,Map<String,List<Map<String,Object>>> stringListMap){ //返回结果
List<Map<String,Object>> result = new ArrayList<>(); //给数据设置属性
for (int i = 0; i < resultList.size(); i++) {
Object o = resultList.get(i);
Object[] cells = (Object[]) o;
Map<String,Object> map = new HashMap<>(); for (int j = 0; j<cells.length; j++) {
map.put((String) fieldNames.get(j),cells[j]);
}
//与前端协议好平均数的机构id赋值上avg
map.put("companyId","avg");
result.add(map);
} for (Map<String, Object> map : result) {
//获取年月的数据
String reportingYear = (String) map.get("reportingYear");
String reportingMonth = (String) map.get("reportingMonth");
String reportingDate = reportingYear+"-"+reportingMonth; //如果时间类型是年
if ("year".equals(timeStyle)) {
List<Map<String, Object>> list = stringListMap.get(reportingYear);
if (list != null) {
/**
* 将相同月份的属性合并在一起
*/
Map<String, Object> objectMap = list.get(0);
objectMap.putAll(map);
stringListMap.put(reportingYear,list);
}else{
List<Map<String,Object>> inner =new ArrayList();
Map<String,Object> field = new HashMap();
for (Map.Entry<String, Object> entry : map.entrySet()) {
field.put(entry.getKey(),entry.getValue());
}
inner.add(field);
stringListMap.put(reportingYear,inner);
}
}else{//如果为月
//查看集合中是否存在该时间段
List<Map<String, Object>> list = stringListMap.get(reportingDate);
/**
* 如果存在,将原本的添加上现在的,不存在就新增一个list添加进去
*/
if (list != null) {
Map<String, Object> objectMap = list.get(0);
objectMap.putAll(map);
stringListMap.put(reportingDate ,list);
}else{
List<Map<String,Object>> inner =new ArrayList();
Map<String,Object> field = new HashMap();
//循环将所有的属性添加进集合
for (Map.Entry<String, Object> entry : map.entrySet()) {
field.put(entry.getKey(),entry.getValue());
}
inner.add(field);
//设置一个新的时间段并添加上该数据
stringListMap.put(reportingDate,inner);
}
} }
} /**
* 设置属性
* @param resultList 结果集合
* @param fieldNames 属性集合
* @param map map封装
* @param num 当前第几个
* @param index 下标
*/
public void setField(List resultList,List fieldNames,Map map,int num,int index){ int i = num;
i++;
if(i>=resultList.size()){
return;
} Object o = resultList.get(i);
Object[] cells = (Object[]) o;
//判断当前这个位置是否存在值,
if (cells[index] != null && !"".equals(cells[index].toString())) {
if(i==resultList.size()){
map.put((String) fieldNames.get(index),null);
}
map.put((String) fieldNames.get(index),cells[index].toString());
}else{
setField(resultList,fieldNames,map,i,index);
} }

我这里是把平均查询和普通的指标的查询区分开了,对应的我对这些数据的操作就增多了。

我这里有用到机构,做的时候不用影响也不会很大,

以前发生一个请求要很久,现在比之前快了许多,所以有关的一些统计的查询和子查询还是要分开的好一点,不然会执行会很慢。可以分开查询,或者后端进行统计之类的。

Java 使用Query动态拼接SQl的更多相关文章

  1. java动态拼接sql语句并且执行时给sql语句的参数赋值

    问题 在这里举一个例子,比如我要做一个多条件模糊查询,用户输入的时候有可能输入一个条件,也有可能输入两个条件,这时执行查询的sql语句就不确定了,但可以用动态拼接sql语句来解决这个问题. 解决方法 ...

  2. 动态拼接 sql的时候 里面 如果有变量的话 按上面的方式进行处理

    set @Sql_Sql = N' select top 1 @m_zw=zw,@m_zh=temp from ket where zd=''ddd'' ' print @Sql_Sql EXEC s ...

  3. python 根据传进来的参数,动态拼接sql

    根据传进来的参数,动态拼接sql,可用于实现一个方法,有些字段不确定,又用到的情况,如查询,三个查询条件,有的时候只用到一个查询条件,其他用不到则不需要拼接 def show_runjob_detai ...

  4. mysql 存储过程动态拼接sql并执行赋值

    )) BEGIN ## 定义变量 ,) ; ## @表示全局变量 相当于php $ ## 拼接赋值 INTO 必须要用全局变量不然语句会报错 SET @strsql = CONCAT('SELECT ...

  5. 动态拼接SQL语句

    1.参考官方文档 ? if:字符判断 ? choose (when, otherwise):分支选择 ? trim (where, set):字符串截取:其中where标签封装查询条件,set标签封装 ...

  6. 使用mybatis提供的各种标签方法实现动态拼接Sql。使用foreach标签实现遍历查询。比如实现select * from user where id in(1,10,24)这条sql查询语句。

    向sql传递数组或List,mybatis使用foreach解析,如下: 需求: 传入多个id查询用户信息,用下边的sql实现: select * from user where id in(1,10 ...

  7. 使用mybatis提供的各种标签方法实现动态拼接Sql。这里演示where标签和if标签实现使用姓名的模糊查询和性别查询用户列表,当用户没有选择姓名以及性别时查询出所有的记录。

    1.需求: 使用姓名的模糊查询和性别查询用户列表,当用户没有选择姓名以及性别时查询出所有的记录. 2.在UserMapper接口中定义方法: public List<User> findU ...

  8. SQL行转列+动态拼接SQL

    数据源       Name AreaName qty Specific 叶玲 1 60 1 叶玲 2 1 1 叶玲 6 1 0 叶玲 7 5 0 叶玲 8 1 1 显示效果: Name 1 2 8 ...

  9. 动态拼接SQL 语句

    public T Get<T>(int id) { Type type = typeof(T); string columnStrings = string.Join(",&qu ...

随机推荐

  1. Android 流媒体播放 live streaming

    安卓支持的协议 RTSP (RTP, SDP)HTTP/HTTPS progressive streamingDynamic adaptive streaming on HTTP => MPEG ...

  2. 通过网站统计或系统监视器查看IIS并发连接数

    如果要查看IIS连接数,最简单方便的方法是通过“网站统计”来查看,“网站统计”的当前在线人数可以认为是当前IIS连接数;如果要想知道确切的当前网站IIS连接数的话,最有效的方法是通过windows自带 ...

  3. Windows搭建Nexus3私服

    1. Nexus 简介 Nexus 是一个强大的 Maven 仓库管理器 , 它极大地简化了自己内部仓库的维护和外部仓库的访问 ; 利用 Nexus 你可以只在一个地方就能够完全控制访问和部署在你所维 ...

  4. nginx请求频率限制模块ngx_http_limit_req_module

    模块: ngx_http_limit_req_module 作用: 限制客户端请求频率,防止恶意攻击 配置示例: http { limit_req_zone $binary_remote_addr z ...

  5. jvm(1)类的加载(二)(自定义类加载器)

    [深入Java虚拟机]之四:类加载机制 1,从Java虚拟机的角度,只存在两种不同的类加载器: 1,启动类加载器:它使用C++实现(这里仅限于Hotspot,也就是JDK1.5之后默认的虚拟机,有其他 ...

  6. Advanced Debugging and the Address Sanitizer

    A debug trick 在异常端点处运行 po $arg1,找出异常信息.  Address Sanitizer 概述 是一个运行时检测工具 发现内存问题 可以用于模拟器和设备 可以发现的问题 ...

  7. centos7在分区上建立文件系统和挂载

    在上一篇博客中,我们只说了硬盘的分区,既然进行分区,那么我们就要知道如何使用这些分区,就是接下来的建立文件系统和挂载. mkfs(make filesystem)格式化,建立文件系统 可以看到各种文件 ...

  8. (转)MySQL 5.6 OOM 问题解决分享

    本文来自:杨德华的原创分享 | MySQL 5.6 OOM 问题解决分享 原文:http://www.cnblogs.com/zhoujinyi/p/5763112.html 延伸阅读:Linux的内 ...

  9. [转]Subdirectory Checkouts with git sparse-checkout

    From:http://jasonkarns.com/blog/subdirectory-checkouts-with-git-sparse-checkout/ If there is one thi ...

  10. Android 开发工具类 07_ScreenUtils

    获得屏幕相关的辅助类: 1.获得屏幕高度: 2.获得屏幕宽度: 3.获得状态栏的高度: 4.获取当前屏幕截图,包含状态栏: 5.获取当前屏幕截图,不包含状态栏. import android.app. ...