多个人做多选题,统计各种选项的百分比
1.首先说一下cekasp_train_survey_option_data表与cekasp_train_survey_option表的关系,以及查询的结果



2.接下来是代码
String countSql = "select count(*) count from cekasp_train_survey_option_data where optionId = ?";
JSONObject countJson = dataService.toJSONObject(countSql, optionId);
double count = countJson.getDouble("count");
String dataSql = "select data from cekasp_train_survey_option_data where optionId = ?";
List<String> dataList = dataService.getSlaveJdbcTemplate()
.queryForList(dataSql, String.class, optionId);
// 把多选的答案拆成单选
List<String> dataNewList = new ArrayList<String>();
JSONArray dataArray = new JSONArray();
JSONObject json = new JSONObject();
for (int i = 0; i < dataList.size();) {
if (dataList.get(i).indexOf("|") > 0) {
String[] data = dataList.get(i).split("\\|");
dataList.remove(dataList.get(i));
for (int k = 0; k < data.length; k++) {
dataNewList.add(data[k]);
}
} else {
dataNewList.add(dataList.get(i));
dataList.remove(dataList.get(i));
}
}
// 统计各种答案的百分比
String optionsSql = "select options from cekasp_train_survey_option where id = ?";
JSONObject option = dataService.toJSONObject(optionsSql, optionId);
String options = option.optString("options");
String value[] = options.split("\\|");
int size = value.length;
for (int i = 0; i < size; i++) {
// 循环获取所有预置值
int dataCount = 0;
String optionValue = value[i];
for (int j = 0; j < dataNewList.size(); j++) {
if (dataNewList.get(j).equals(optionValue)) {
dataCount++;
}
}
double percent = dataCount / count * 100;
DecimalFormat df = new DecimalFormat("0.00");
JSONObject data = new JSONObject();
data.put("percent", df.format(percent));
data.put("value", optionValue);
data.put("count", dataCount);
dataArray.put(data);
}
json.put("reportData", dataArray);
return json;
3.最后贴上测试结果
"reportData": [
{
"percent": "75.00",
"count": 3,
"value": "Education"
},
{
"percent": "25.00",
"count": 1,
"value": "123"
},
{
"percent": "75.00",
"count": 3,
"value": "789"
}
]

浙公网安备 33010602011771号