2010-01-15 46 views
0

我有一個表以下字段 SERVICE_TYPE和consumer_feedback.for例如,所有查詢:總和和工會用mysql和Java

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

我想通過java代碼找到consumer_feedback的每個的Service_ID總和

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); 
} 

但這種代碼工作FOR2的Service_ID的,而不是三個Service_ID's.Please幫我出

+1

如果您需要幫助,請正確設置代碼的格式 – 2010-01-15 04:22:52

回答

1

您的查詢應該是

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

這將消除需要做聯合。