___WORKER_ID___|_______OCCUR________
20 | 1
20 | 2
21 | 3
22 | 5
20 | 1
According to this table, I need to know each worker how many occur?
Such as Worker_id=20 has occur is 4
Worker_id=21 has occur is 8
我可以通过此代码从这个Worker表中获取两个值
String sql = "SELECT Table.worker_id,Table.occur FROM keyword_pages Table"
+ " WHERE keyword_id=" + PUID;
conn = getConnection();
stm = conn.createStatement();
rs = stm.executeQuery(sql);
while (rs.next()) {
int kwd_id = rs.getInt(1); /**Worker_id is 20,20,21,22,20*/
int occur = rs.getInt(2); /**Worker_id is 1,2,3,5,1*/
}
如何获得每个工人的发生量?
这是我的编码。 我使用hashmap存储每条记录。 并将hashmap存储到linklist。但我对获得结果没有任何想法。
conn = getConnection();
stm = conn.createStatement();
rs = stm.executeQuery(sql);
while (rs.next()) {
int kwd_id = rs.getInt(1);
int occur = rs.getInt(2);
hMap.put(kwd_id, occur);
listID.add(hMap);
//System.out.println(kwd_id +" | "+ occur);
}
for (int i = 0; i < listID.size(); i++) {
}
答案 0 :(得分:2)
String sql = "SELECT T.worker_id, SUM(T.occur) AS osum"
+ " FROM keyword_pages T"
+ " WHERE keyword_id=" + PUID
+ " GROUP BY T.worker_id";
现在rs.getInt(2)
或rs.getInt("osum")
会给出小组的总和。
答案 1 :(得分:1)
Map<Integer,Integer> id2count = new HashMap<>();
while (rs.next()) {
int kwd_id = rs.getInt(1); /**Worker_id is 20,20,21,22,20*/
int occur = rs.getInt(2); /**Worker_id is 1,2,3,5,1*/
Integer count = id2count.get( kwd_id );
if( count == null ){
count = Integer.valueOf( 1 );
} else {
count += occur;
}
id2count.put( kwd_id, count );
}
**后来**
检索和打印累计值的代码:
for( Integer key: id2count.keySet() ){
System.out.println( key + ": " + id2count.get(key) );
}