Skip to content
Advertisement

Create table which shows earliest and latest date for same names(IDs)

So from my table where I have columns: name, date

I would like to select names that repeat point out how many times they repeat and then from the rows with same names I want to print out earlies and latest date for that name.

After all my table would have columns: name, how many, earliest date, latest date

I am not sure though if MIN and MAX functions will take into consideration values only from places with the same name or they will take into consideration all the fields.

Do I need to add additional WHERE statements for MIN and MAX functions so they only choose fields with the same names?

sample database that I will be using is:

Advertisement

Answer

First, the correctly formed query looks like:

Notes:

  • The WHERE clause goes immediately after the FROM clause. The ordering of clauses is important.
  • Column aliases cannot have spaces unless you wrap them in escape characters. Just use an underscore.
  • Although count(name) is fine, count(*) is more convenient for just counting rows.

As for your question: The aggregation functions only return values based on rows that match the group. If you wanted overall numbers, you could use window functions in combination with them:

Note that the “overall” numbers are only for the rows that are not filtered out by the WHERE and HAVING clauses.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement