sum和union使用mysql和java查询所有查询

时间:2010-01-15 04:10:42

标签: mysql

我有一个包含以下字段的表格 Service_type和consumer_feedback.for例如:

Service_ID  consumer_feedback
31           1
32           -1
33            1
31            1
32            1.

我想通过java代码

找到每个Service_ID的consumer_feedback总和
ResultSet res = st.executeQuery("SELECT SUM(consumer_feedback) 
                                   FROM  consumer1 
                                  where Service_ID=31 
                                 union  
                                 SELECT SUM(consumer_feedback)  
                                   FROM consumer1 
                                  where Service_ID=32 
                                 union  
                                 SELECT SUM(consumer_feedback)  
                                   FROM consumer1 
                                 where Service_ID=33") ;
    while (res.next()) {
      int c1 = res.getInt(1);           
      sum1 = sum1 + c1;        
    }

    System.out.println("Sum of column "   +sum1);

    while (res.next()) {
      int c2 = res.getInt(1);           
      sum2 = sum2 + c2;                  
    }

    System.out.println("Sum of column "   +sum2);

    while (res.next()) {
      int c3 = res.getInt(1);
      sum3 = sum3 + c3;
    }

    System.out.println("Sum of column "   +sum3);
}

但是这段代码适用于2个Service_ID,而不适用于三个Service_ID。请帮我解决

1 个答案:

答案 0 :(得分:1)

您的查询应该是

select service_id,sum(consumer_feedback) from consumer1 group by service_id

这将消除对工会的需要。