开发者

sum and union all query using mysql and java

开发者 https://www.devze.com 2022-12-16 17:12 出处:网络
I have a table with following fields Service_type and consumer_feedback.for example: Service_IDconsumer_feedback

I have a table with following fields Service_type and consumer_feedback.for example:

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

I want to find the sum of consumer_feedback for each Service_ID through java code

ResultSet res = st.executeQuery("SELECT SUM(consumer_feedback) 
                                   FROM  consumer1 
                                  where Service_ID=31 
                                 union  
                                 SELECT SUM(consumer_feedback)  
                                   FROM consumer1 
                                开发者_StackOverflow社区  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);
}

But this code is working for2 Service_ID's and not for three Service_ID's.Please help me out


Your query should be

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

This will eliminate the need to do the unions.

0

精彩评论

暂无评论...
验证码 换一张
取 消