Skip to Main Content

Database Software

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

SQL Syntax: GROUP BY OTHERS

Matheus BoesingJul 2 2016 — edited Jul 28 2016

When writing a SQL with aggregate/group functions (SUM, COUNT, AVG, etc) is actually needed to put all other columns in GROUP BY clause. If you want to put another column in select statement, it’s obligated to put it on GROUP BY too.

So, to make it simplier, it could exists a "GROUP BY OTHERS" that group all selected columns that are not under aggregate functions, like:

SELECT COUNT(*), SUM(salary), AVG(salary), AVG(age), company, state, country FROM company_employees GROUP BY OTHERS;

It's way simpler (and not repeated) than the actual:

SELECT COUNT(*), SUM(salary), AVG(salary), AVG(age), company, state, country FROM company_employees GROUP BY company, state, country;

And if you want to add another column, you just want to add in select, not in group by, like:

SELECT COUNT(*), SUM(salary), AVG(salary), AVG(age), company, state, country, continent FROM company_employees GROUP BY OTHERS;

It makes much more easier and avoids the error: ORA-00979: not a GROUP BY expression

By the way, I think this error mainly occur because of ‘forget’ than bad SQL. When the SQL syntax is not helping but disturbing, it’s not good and need to be improved.

Comments
Post Details
Added on Jul 2 2016
18 comments
762 views