Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does my SQL Statement not SUM() up correctly?

I have the following statement:

SELECT 
   ROUND(SUM(invoicetitle.unitpricegross*invoicetitle.suppliedquantity),2) as Costs,
   SUM(invoicetitle.suppliedquantity) AS Unitamounts 
FROM invoicetitle 
WHERE 
  ((SELECT invoice.state 
    FROM invoice where invoicetitle.invoiceid = invoice.invoiceid 
     and (invoice.invoicedate >= 1609459200000 and invoice.invoicedate <= 1640908800000)) = (1 or 4)) 
GROUP BY invoicetitle.invoicetitle_number

note that = (1 or 4) refers to two statements in the database where 1 is sold and 4 is a refund.

With = (1)) I get the following results:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Costs – Unitamounts
3.281,10 – 582

With = (4)) I get the following results:

Costs – Unitamounts
-115,2 – -32

With = (1 or 4)) I get the following results:

Costs – Unitamounts
3.281,10 – 582

But I expect as a correct SUM() of it:

Costs – Unitamounts
3.165,9 – 550

What am I doing wrong that the results are not subtracted correctly?

>Solution :

You probably meant to do:

SELECT 
   ROUND(SUM(invoicetitle.unitpricegross*invoicetitle.suppliedquantity),2) as Costs,
   SUM(invoicetitle.suppliedquantity) AS Unitamounts 
FROM invoicetitle 
INNER JOIN invoice ON invoicetitle.invoiceid = invoice.invoiceid 
          and (invoice.invoicedate BETWEEN 1609459200000 
                                      and  1640908800000)
WHERE invoice.state IN (1,4)
GROUP BY invoicetitle.invoicetitle_number
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading