2
Hello, I am self-taught and already do some consultations in SQL but "stuck" in this.
I need a list where one of the fields should show the total of a column, minus the total of another that is in a second table.
Example:
Table A (Invoices)
+------+---------+------------+------------+
| id | docnum | valor | clienteid |
+------+---------+------------+------------+
1 25 150,00 23
2 26 300,00 22
3 27 450,25 23
3 28 600,00 23
Table B (Receipts)
+------+---------+------------------+-----------------------+--------+
| id | docnum | numfac | valor | valorpago| clienteid | Tipo |
+------+---------+------------------+-----------------------+--------+
1 1 25 150,00 150,00 23 REC
2 2 27 450,25 100,00 23 REC
3 25 45 -25,00 -25,00 23 FAL
4 3 27 450,25 100,00 23 REC
5 88 78 55,25 -55,25 23 FAL
The Table To contains the Invoices issued
The Table B Contains the Paid Amounts
I need to get a listing of outstanding invoices by taking partial payments and ignoring those that are already paid.
The result should be as follows:
Cliente ValorDocumento ValorEmDebito
22 300,00 300,00
23 1000,25 800,25
if you use this query:
SELECT f.docnum AS Doc,
f.clienteid AS Cliente,
f.valor AS ValorDocumento,
f.valor - SUM(COALESCE(r.valorpago, 0)) As ValorEmDebito
FROM Facturas f
LEFT JOIN Recibos r
ON r.numfac = f.docnum
WHERE (r.tipodoc IS NULL or r.tipodoc='rec' ) and f.clientid=23
GROUP BY f.docnum,
f.clienteid,
f.valor
HAVING f.valor - SUM(COALESCE(r.valorpago, 0)) > 0;
filtering by the customer 23 only partially paid invoice appears
Cliente ValorDocumento ValorEmDebito
23 450,25 250,25
and wanted it to appear
Cliente ValorDocumento ValorEmDebito
23 1000,25 600,25
What the
SGBD
used?– Sorack
Hi, I’m using the TADO Delphi XE7
– ONosso Tone
That’s not the
SGBD
. I’m asking if you’re usingMySQL
,SQL Server
,Oracle
...– Sorack
But man, you’re doing it
WHERE
by customer 23... customer 23 only has an invoice that is fully paid and a partial, there is no way to show the 300,00 if it is not the customer you specified inWHERE
– Sorack
And in real as will appear 350,25 if he paid 2x 100,00
– Sorack
You’re Right, I Already Reformulated... is that I’ve been in this for days and the brain one day rescinds contract
– ONosso Tone
Ah, you want per customer, not per document. This completely changes the solution
– Sorack
It Was My Mistake ... I’m so sorry for the confusion
– ONosso Tone