sql中一列的所有值的总和

时间:2013-12-20 13:52:10

标签: java sql sum

我需要获取一列的所有值的总和并将其放在textField中。我尝试下面的代码,但我收到一个错误。 - 列名Sum(价格)无效。

     String sql="Select Sum(Price) from sold";
                              pst=con.prepareStatement(sql);
                              rs=pst.executeQuery();
                              if(rs.next()){
                                  String sum = rs.getString("Sum(Price)");
                                  textField_2.setText(sum);

com.microsoft.sqlserver.jdbc.SQLServerException: The column name Sum(Price) is not valid.

4 个答案:

答案 0 :(得分:2)

使用别名:

 String sql="Select Sum(Price) as sumprice from sold";
                          pst=con.prepareStatement(sql);
                          rs=pst.executeQuery();
                          if(rs.next()){
                              String sum = rs.getString("sumprice");
                              textField_2.setText(sum);

我不知道这些值是否正确转换。该值是某种数字。也许你想要:

 String sql="Select cast(Sum(Price) as varchar(255)) as sumprice from sold";

答案 1 :(得分:1)

使用计算列的别名

Select Sum(Price) as sum_price from sold
...
String sum = rs.getString("sum_price");
textField_2.setText(sum);

答案 2 :(得分:0)

默认情况下,使用带有序数列号的重载作为聚合的结果是无名的: rs.getString(1)

答案 3 :(得分:0)

试试这个。

        int sum = 0;
        Statement st = conn.createStatement();
        ResultSet res = st.executeQuery("SELECT SUM(price) FROM sold");
        while (res.next()) {
        int c = res.getInt(1);
        sum = sum + c;

        String str = Integer.toString(sum);
        textField_2.setText(str);

这将起作用