Skip to content
Advertisement

Query returning data outside the scope of the WHERE condition

I’m trying to retrieve summarized data from the table depending on DateTime and state. The problem is I need multiple state values ex. ‘where 1 or 2 or 3’

SELECT SUM(ticketTotalAmount)
FROM tickets 
WHERE ticketDate >= '2019/04/01 00:00:00' AND ticketDate <= '2019/04/02 23:59:59'
  AND ticketState = 'STAND BY'
   OR ticketState = 'WIN'
   OR ticketState = 'LOSE'

The output should retrieve summarized data based on any of those 3 states, Win, Lose or Standby and in the range of the ticketDate but the actual output is beyond the scope of DateTime restrictions.

Removing the state conditions and leaving only the DateTime retrieves data within the scope of the condition. The problem is there are more than these 3 states.

Advertisement

Answer

The problem is the order of the AND and OR clauses.

Try this:

SELECT SUM(ticketTotalAmount)
FROM   tickets 
WHERE  ticketDate >= '2019/04/01 00:00:00' AND ticketDate <= '2019/04/02 23:59:59' AND
       (ticketState = 'STAND BY' OR ticketState = 'WIN' OR ticketState = 'LOSE');

Or even better:

SELECT SUM(ticketTotalAmount)
FROM   tickets 
WHERE  ticketDate BETWEEN '2019/04/01 00:00:00' AND '2019/04/02 23:59:59'
  AND  ticketState IN ('STAND BY', 'WIN', 'LOSE');
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement