Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Databases

SQL

Having a hard time wrapping my brain around this.

Suppose I have a table like this

1 Answer

Steven Parker
Steven Parker
231,269 Points

The result set will have a separate row for each unique combination of items being grouped by. So don't include the date in the grouping:

SELECT name, date, MAX(amount) 
FROM sample
GROUP BY name

Thanks Steven! The issue with that is when I try and run this, I receive the following error:

ERROR: column "sample.date" must appear in the GROUP BY clause or be used in an aggregate function

I'm assuming that is where a subquery comes in, but that is where I'm having a hard time seeing how that would work.

Steven Parker
Steven Parker
231,269 Points

If you are using a database engine that does not allow you to select a column that isn't being grouped or aggregated (not an issue with SQLite), you could use your subquery idea:

SELECT name, date, amount
FROM sample s
WHERE amount = (SELECT MAX(amount) from sample WHERE name = s.name)

Sweet, that second one did it! Thanks so much, going to sit with this one for a bit :)