如何从数据库中检索一列数据的总和?

时间:2014-03-05 19:58:27

标签: java database swing

如何从数据库中检索一列数据的总和并从数据库的另一列数据中删除它?我想这样做,从Total_Sales列获取总和并从Total_Value列获得总和并执行子操作,即从Total_Sales(Total_Sales - Total_Value)的值中减去Total_Value的值。目前这是我的一段代码。

calculateButton.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent ae)
    {

    try
    {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection conn = DriverManager.getConnection("Jdbc:Odbc:TomsJava");

        java.util.Date fromDate=(java.util.Date)fromtextField.getValue();
        java.util.Date toDate=(java.util.Date)totextField.getValue();

        PreparedStatement ps = conn.prepareStatement("select SUM(Total_Sales - Total_Value) As Result from DailyAnalysis where 'Date1 BETWEEN #fromDate# AND #toDate#' ");
        ResultSet rs = ps.executeQuery();
        while(rs.next())
        {

            String itemName = rs.getString("Item");
            Double totalValue = rs.getDouble("Total_Value");
            Double totalSales = rs.getDouble("Total_Sales");

            Double Result = rs.getDouble(1);

        }

    }
    catch(SQLException s)
    {
        System.out.println(s);
    }
    catch(ClassNotFoundException z)
    {
        System.out.println(z);
    }
    catch(NumberFormatException n)
    {
        System.out.println(n);
    }
    }
    });

enter image description here

EDITS 我试图检索两个日期之间的列。我想将Total_Value的检索值总和设置为Total Expense文本字段,并将Total_Sales列的总和设置为Total Income文本字段。然后根据它计算盈利或亏损。

1 个答案:

答案 0 :(得分:2)

Select Sum(Total_Sales) as Sales_Total, Sum(Total_Value) as Value_Total, Sum(Total_Sales - Total_Value) as Result
From DailyAnalysis

将查询和代码更改为此

     Double result = null;
     Double totalValue = null;
     Double totalSales = null;
      ...

      PreparedStatement ps = conn.prepareStatement("select Sum(Total_Sales) as Sales_Total, Sum(Total_Value) as Value_Total, SUM(Total_Sales - Total_Value) As Result from DailyAnalysis where Date1 BETWEEN ? AND ? ");
            ps.setDate(1,fromDate)
            ps.setDate(2,toDate)
            ResultSet rs = ps.executeQuery();

            //Query should only return one or zero result hence the if statement
            if (rs.next())
            {  
               //Define variables at the top, if you want to have access outside the if block scope
               totalValue = rs.getDouble("Value_Total");
               totalSales = rs.getDouble("Sales_Total");
               result = rs.getDouble("Result");
            }