I have a problem with this code:
im = stat.executeQuery("SELECT * FROM imones");
while (im.next()) {
sask = stat2.executeQuery("SELECT * FROM saskaitos WHERE imone='" + im.getInt("id") + "'");
while (sask.next()) {
suma = suma + Integer.parseInt(sask.getString("suma"));
kvit = stat3.executeQuery("SELECT * FROM kvitai WHERE sask_nr='" + sask.getInt("sask_nr") + "'");
while (kvit.next()) {
suma = suma - Integer.parseInt(kvit.getString("suma"));
}
kvit.close();
}
sask.close();
//if (suma > 0) {
imone = im.getString("pav");
skola = suma;
DefaultTableModel y = (DefaultTableModel) pagrindinis.visos_skolos_table.getModel();
Vector rowData = new Vector();
rowData.add(imone);
rowData.add(skola);
y.addRow(rowData);
//}
}
im.close();
I get only one loop ( while (im.next()) ) because 'sask' query has no results and it closes 'im' resultset and multi Statements not helping. How can I get this code working? Thank you!
The nested loops are not required, this can be done with one SQL statement that joins the table and sums the amounts. I obviously don't have all the column names at my disposal but you should be able to replace the names I've used with your own:
SELECT company.name,
SUM(bill.amount) - SUM(cheque.amount) AS amount
FROM imone AS company
INNER JOIN saskaitos AS bill ON company.id = bill.imone
LEFT JOIN kvitai AS cheque ON bill.sask_nr = cheque.sask_nr
GROUP BY company.name;