用2个标准计算不同的值

时间:2018-02-21 08:13:39

标签: java mysql jdbc

我正在尝试查找JDBC MySQL查询,该查询将在特定字段中查找不同的值,计算该反馈的出现次数,然后将其存储在数组列表中(如果可能或存在更好的存储方式)

Company      Feedback    Person
------       --------    ------
Apple        Good          A
Pear         Bad           B
Apple        Neutral       C
Orange       Neutral       D
Apple        Bad           E
Apple        Neutral       F
Orange       Bad           G

Apple的预期结果

Company     Feedback     Count
-------     --------     -----
Apple       Good           1
Apple       Neutral        2
Apple       Bad            1

编辑添加我的代码:

//Already call an object from database
rs = db.getSM().executeQuery("SELECT COUNT(*) AS 
rowcount FROM predata WHERE company = 'Apple' and feedback LIKE 'G%'");
rs.next();
System.out.println(rs.getInt("rowcount"));

rs = db.getSM().executeQuery("SELECT COUNT(*) AS 
rowcount FROM predata WHERE company = 'Apple' and sentiment LIKE 'N%'");
rs.next();
System.out.println(rs.getInt("rowcount"));

这种方法对我有用,但我试图缩短整个代码而不重复代码

2 个答案:

答案 0 :(得分:0)

SELECT  Company, Feedback, COUNT(Feedback)
FROM t
GROUP BY Feedback
where Company='Apple';

答案 1 :(得分:0)

您可以一次查询所有公司反馈对,并将其存储在Map

使用数据库中的计数查询所有对。

rs = db.getSM().executeQuery("SELECT company, feedback, COUNT(DISTINCT person) AS rowcount FROM predata GROUP BY company, feedback");

创建Map并循环浏览ResultSet以存储计数。

HashMap<String, HashMap<String, Integer>> companyFeedbackMap = new HashMap<String, HashMap<String, Integer>>();
while (rs.next()) {
    String company = rs.getString("company");
    String feedback = rs.getString("feedback");
    Integer count = rs.getInt("rowcount");
    if(!companyFeedbackMap.contains(company)){
        companyFeedbackMap.put(company, new HashMap<String, Integer>());
    }
    companyFeedbackMap.get(company).put(feedback, count);
}

要获得Apple公司的Neutral反馈计数,只需使用companyFeedbackMap.get("Apple").get("Neutral"); // This will return 2

或者,您可以创建自己的HashMap<String, HashMap<String, Integer>>类,而不是Company,其中包含公司名称goodneutralbad作为其构造函数属性,将来自透视查询sql的计数存储在ArrayList或您需要的任何内容中,例如

rs = db.getSM().executeQuery("SELECT company, SUM(good) AS good, SUM(neutral) AS neutral, SUM(bad) AS bad FROM (SELECT company, CASE WHEN feedback = 'Good' THEN 1 ELSE 0 END AS good, CASE WHEN feedback = 'Neutral' THEN 1 ELSE 0 END AS neutral, CASE WHEN feedback = 'Bad' THEN 1 ELSE 0 END AS bad FROM predata) GROUP BY company");
ArrayList<Company> companies = new ArrayList<Company>();
while (rs.next()) {
    String company = rs.getString("company");
    Integer good = rs.getInt("good");
    Integer neutral = rs.getInt("neutral");
    Integer bad = rs.getInt("bad");
    companies.add(new Company(company, good, neutral, bad));
}

上面的sql将返回以下结果。

Company      good        neutral    bad
------       --------    -------    -------
Apple        1           2          1
Orange       0           1          1
Pear         0           0          1