Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use non-aggregate columns with group by?

You cannot (should not) put non-aggregates in the SELECT line of a GROUP BY query.

I would however like access the one of the non-aggregates associated with the max. In plain english, I want a table with the oldest id of each kind.

CREATE TABLE stuff (
   id int,
   kind int,
   age int
);

This query gives me the information I'm after:

SELECT kind, MAX(age)
FROM stuff
GROUP BY kind;

But it's not in the most useful form. I really want the id associated with each row so I can use it in later queries.

I'm looking for something like this:

SELECT id, kind, MAX(age)
FROM stuff
GROUP BY kind;

That outputs this:

SELECT stuff.*
FROM
   stuff,
   ( SELECT kind, MAX(age)
     FROM stuff
     GROUP BY kind) maxes
WHERE
   stuff.kind = maxes.kind AND
   stuff.age = maxes.age

It really seems like there should be a way to get this information without needing to join. I just need the SQL engine to remember the other columns when it's calculating the max.

like image 439
deft_code Avatar asked Jul 02 '10 17:07

deft_code


People also ask

Can you use GROUP BY without aggregate?

GROUP BY without Aggregate Functions Although most of the times GROUP BY is used along with aggregate functions, it can still still used without aggregate functions — to find unique records.

Is aggregate function mandatory for GROUP BY?

If you don't specify GROUP BY , aggregate functions operate over all the records selected. In that case, it doesn't make sense to also select a specific column like EmployeeID .

What column data type can't you include in a GROUP BY?

You don't list columns that are inside aggregate functions in GROUP BY .

Can aggregate functions be used with HAVING but not GROUP BY?

Having can be used without groupby clause,in aggregate function,in that case it behaves like where clause.


1 Answers

You can't get the Id of the row that MAX found, because there might not be only one id with the maximum age.

like image 181
Blorgbeard Avatar answered Oct 01 '22 02:10

Blorgbeard