我希望选择一个表的子集
然后我想计算这个子集中的记录数
最后得到一个特定字段的总和
我的代码如下: -
// get the subset of records in the XXXXXX table
ps = conn.prepareStatement("SELECT Field1, Field2, Field3 FROM XXXXXXX "
+ "WHERE Field1 = ? AND Field2 = ? AND Field3 = ? "
+ "GROUP BY Field1, Field2, Field3");
ps.setString(1, variable1);
ps.setString(2, variable2);
ps.setString(3, variable3);
rs = ps.executeQuery();
int recordCount1 = 0;
while (rs.next()) {
recordCount1 = recordCount1 + rs.getInt(1);
}
rs.close();
ps.close();
myConsole.getOut().println("Number of records in Subset1 of table
XXXXXXX: " + recordCount1);
// now split the subset into those records where P/L > 0
and those records where P/L <0
// positive P/L
ps = conn.prepareStatement("SELECT Field1, Field2, Field3 "
+ "SUM(PL) AS Total_Profit FROM XXXXXX "
+ "WHERE Field1 = ? AND Field2 = ? AND Field3 = ? "
+ "AND PL >= 0 "
+ "GROUP BY Field1, Field2, Field3");
ps.setString(1, variable1);
ps.setString(2, variable2);
ps.setString(3, variable3);
rs = ps.executeQuery();
int recordCount2a = 0;
while (rs.next()) {
recordCount2a = recordCount2a + rs.getInt(1);
}
myConsole.getOut().println("Number of records in Subset of table
XXXXXX where P/L >= 0: " + recordCount2a);
我对子集
中的记录数进行零计数代码区域是否有错误?
答案 0 :(得分:0)
首先查询。 - &GT;显示计数FIELD1
SELECT FIELD1, COUNT(FIELD1) FROM XXXXX
WHERE FIELD1= ? AND FIELD2=? AND FIELD3=?
GROUP BY FIELD1
第二个查询 - &gt;显示FIELD1的计数及其PL SUM
SELECT FIELD1, COUNT(FIELD1), SUM(PL) AS Total_Profit FROM XXXXX
WHERE FIELD1= ? AND FIELD2=? AND FIELD3=? AND PL > 0
GROUP BY FIELD1