gpt4 book ai didi

java - 如何从数据库中检索某列数据的总和?

转载 作者:行者123 更新时间:2023-12-02 06:06:49 27 4
gpt4 key购买 nike

如何从数据库中检索一列数据的总和并从数据库中的另一列数据中减去它?我想要这样做,从 Total_Sales 列中获取总和,从 Total_Value 列中获取总和,然后执行减法运算,即从 Total_Sales 值中减去 Total_Value 值(Total_Sales - 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

编辑我正在尝试检索两个日期之间的列。我想将 Total_Value 的检索值总计设置为“总费用”文本字段,并将 Total_Sales 列的总和设置为“总收入”文本字段。然后据此计算利润或损失。

最佳答案

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

关于java - 如何从数据库中检索某列数据的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22207922/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com