Search code examples
sqlwhere-clausehaving

SQL Tickets sold - Last 30 Days - use Where or Having?


How many tickets were sold for each route and each day, for the routes sold in the last 30 days from current day?

SELECT COUNT(TICKET_ID) NUMBER_TICKETS, ROUTE_CODE, FLIGHT_DATE 
FROM TICKETS 
WHERE (DAYS(CURRENT DATE)- DAYS(FLIGHT_DATE))<=30
GROUP BY ROUTE_CODE, FLIGHT_DATE

Should this be WHERE or HAVING? I am not sure which way is correct?


Solution

  • You want it in the WHERE.

    Here is the best way to understand this --

    The WHERE clause is used before the GROUP BY

    The HAVING clause is used after the GROUP BY

    So -- you want to group items in the last 30 days -- that happens before the group.