top of page

Can I use MAX(COUNT()) in SQL?

  • Quynh
  • Jun 4, 2017
  • 2 min read

I came across an interesting SQL challenge that looked easy first and then proved to be a bit tricker than expected.

And the short answer to the above question is, no. You can't. It is not possible to nest aggregate functions.

So, I have a list with all the guests that appeared on the DailyShow from 1999 - 2015. The dataset includes the date/year of the show, guest name, and their occupation.

The question is:

What was the most popular profession of guest for each year Jon Stewart hosted the Daily Show?

This is the table schema:

First, let's find out the most common occupation over ALL the years:

Easy enough. The result:

So far so good. Now, how do we get this result by year?

To start, let's get the occupation count by year for each profession:

The result is the occupation count for each occupation for each year:

Now how do we limit these results for each year to the highest occupation count?

We'd expect to use MAX on COUNT(occupation) and add the year to the GROUP BY. Something like this:

Uh-oh.

Hm, another try is to use a WHERE clause:

Nope.

So how can we find an alternative to the MAX(COUNT()) that we are dreaming of?

The solution is to use the first table as a subquery. We will create an additional query, an outer query, which uses the first table in its FROM clause. It will be able to use MAX() on the COUNT() result from the first table, thus circumventing the direct use of two layered aggregate functions.

1./ Inner query > Reminder, this is how it looked like:

2./ Outer Query > Now we are creating an ALIAS "occupation_count" for COUNT(occupation) column in the inner query so that we can reference it from the outer query.

And voila, there we have it:

The problem was that it is not allowed to use two aggregate functions in the SELECT statement. The solution is to create a table to get the results from the inner function first, and then use this table for calling the second function on the respective column.

Data can be found on github:

Comments


You Might Also Like:
IMG_20170609_201523
Screen Shot 2017-06-06 at 4.06.27 PM
Screen Shot 2017-06-11 at 11.45.13 AM
IMG_1521
IMG_20170518_185655
IMG_20170519_173940
IMG_20170515_164604
IMG_20170518_183205
IMG_20170518_183126
IMG_20170518_183254
IMG_20170503_153032
IMG_20170518_182930
IMG_20170519_074026
flatiron-school-51
IMG_20170518_183215
Hi,

I am Quynh. Recently, I took an exciting decision: I want to become a software developer.

Follow me on my journey! It starts at a coding bootcamp in New York...

 

Read More

 

bottom of page