Home > Software engineering >  SQL Tickets sold - Last 30 Days - use Where or Having?
SQL Tickets sold - Last 30 Days - use Where or Having?

Time:03-02

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?

CodePudding user response:

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.

CodePudding user response:

where is the right command, consider to use "datediff" for calculate 30 days

CodePudding user response:

the WHERE clause is used to specify a condition for filtering records before any groupings are made the HAVING clause is used to specify a condition for filtering values from a group

in this case, the where clause is used for filtering the condition, not the group. You should use "having",for example, if you wanted to check the ticket_id.

  • Related