【问题标题】:Sum of all values of one column from sqlsql中一列的所有值的总和
【发布时间】:2013-12-20 13:52:10
【问题描述】:

我需要获取一列的所有值的总和并将其放入文本字​​段中。我尝试了下面的代码,但出现错误。 - 列名 Sum(Price) 无效。

     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.

【问题讨论】:

    标签: java sql sum


    【解决方案1】:

    使用别名:

     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";
    

    【讨论】:

      【解决方案2】:

      为计算列使用别名

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

      【讨论】:

        【解决方案3】:

        使用将序号作为聚合结果的重载默认是无名的: rs.getString(1)

        【讨论】:

          【解决方案4】:

          试试这个。

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

          这会起作用

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-03-05
            • 2014-08-29
            相关资源
            最近更新 更多