0

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:

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?

3
  • 2
    use IsNull (field,0) to check for null. The subquery looks strange. use the where exists instead Commented Feb 9, 2022 at 15:28
  • 4
    Change = (1 or 4) to IN (1,4), see IN Commented Feb 9, 2022 at 15:29
  • 1
    What is happening is the expression (1 OR 4) is being evaluated as boolean (true) so the return value is 1. Consider SELECT (3 OR 4) returns 1. The expression foo = (3 OR 4) is equivalent to foo = 1. Commented Feb 9, 2022 at 15:46

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

thank you this helped me a lot

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.