简体   繁体   English

SQL表的子集-记录数和一个字段的总和

[英]Subset of a sql table - number of records and sum of a field

I wish to select a subset of a table 我希望选择一个表的子集

I then want to count the number of records in this subset 然后,我想计算该子集中的记录数

And finally get the sum of one particular field 最后得到一个特定领域的总和

My code is as follows:- 我的代码如下:

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

I am getting a zero count for the number of records in the subset 我得到的子集中记录数为零

Are there areas of the code which are incorrect ? 代码中是否存在不正确的区域?

First query. 首先查询。 -> Display count FIELD1 ->显示计数FIELD1

SELECT FIELD1, COUNT(FIELD1) FROM XXXXX
WHERE FIELD1= ? AND FIELD2=? AND FIELD3=?
GROUP BY FIELD1

Second query -> Display count of FIELD1 and its PL SUM 第二个查询->显示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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM