1

I have a table called 'games' that has a column in it called 'week'. I am trying to find a single query that will give me the maximum value for 'week' along with a count of how many rows in that table have the maximum value for 'week'. I could split it up into two queries:

SELECT MAX(week) FROM games
// store value in a variable $maxWeek
SELECT COUNT(1) FROM games WHERE week = $maxWeek
// store that result in a variable

Is there a way to do this all in one query?

1 Answer 1

4
SELECT week, count(*) FROM games GROUP BY week ORDER BY week DESC LIMIT 1;

or

SELECT week, count(*) FROM games WHERE week = (SELECT max(week) FROM games) GROUP BY week;

(may be faster)

Sign up to request clarification or add additional context in comments.

2 Comments

I went with the second one, and I must admit I thought about using GROUP BY and ORDER but didn't think it would work. :P
Why wouldn't it? ;-) Have you checked with explain if the second one is better? Just wondering…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.