0

I want to Select the same range of dates and group them by year. In this case I want the total of the bills of a customer per year from September and October.

My Code right now:

SELECT c.name, c.telefonnumber, TO_CHAR(b.billdate, 'YYYY'), sum(b.sume)
FROM customer c, bill b
WHERE b.customerId = c.id
AND b.datum BETWEEN '01.10.2016' AND '30.09.2016'
GROUP BY c.name, c.telefonnumber, TO_CHAR(b.billdate, 'YYYY');

This Query works perfectly but when I want to add another year the result is an endless loop:

AND b.datum BETWEEN '01.10.2016' AND '30.09.2016'
OR b.datum BETWEEN '01.10.2015' AND '30.09.2015'

I also tried to do it in a String way. In this case when I only look for the results of September it works perfectly, but again as soon as I add the OR it becomes again an endless loop:

AND TO_CHAR(kp.tmstmp) LIKE '%.09.%' 
OR TO_CHAR(kp.tmstmp) LIKE '%.10.%' 

I know I am somehow missing something in the OR operator, but since this is only happening me with dates I am a bit confused.

1
  • When mixing AND and OR you should really use brackets around the things you are ORing. A common mistake to make and it's what is causing your query to hang. Commented Nov 23, 2017 at 11:26

2 Answers 2

2

This query works fine and return 0 rows, I guess - exactly the number of dates between 01.10.2016 and 30.09.2016 :)

If you wish to check several ranges, you should enclose them into braces:

... and
  ( 
    b.datum between date '2016-10-01' and date '2017-09-30' or
    b.datum between date '2015-10-01' and date '2016-09-30' or
    ... 
  ) and
...
Sign up to request clarification or add additional context in comments.

Comments

0

It looks like your date criteria in the WHERE clause are being phrased incorrectly. Try this instead:

SELECT c.name, c.telefonnumber, TO_CHAR(b.billdate, 'YYYY'), sum(b.sume)
FROM customer c, bill b
WHERE b.customerId = c.id AND
      (b.datum BETWEEN TO_DATE('01.10.2016', 'DD.MM.YYYY') AND
                      TO_DATE('30.09.2016', 'DD.MM.YYYY') OR
       b.datum BETWEEN TO_DATE('01.10.2015', 'DD.MM.YYYY') AND
                      TO_DATE('30.09.2015', 'DD.MM.YYYY'));

I made two changes, namely making certain that the date checks occur in one logical place, surrounded by outer parentheses, and that we use bona fide dates when comparing against the datum column.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.