Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL return count(*) column along side of regular column?

Tags:

sql

count

oracle

In Oracle SQL, how do I return count(*) column along side of a regular column?

What works:

select count(*) from TABLE where username = 'USERNAME';

What I'd like to work:

select username,count(*) from TABLE where username = 'USERNAME';

So I want the username along side of the count, to expand this into another query that lists numerous usernames and the count of their records.

Error:

ORA-00937: not a single-group group function
00937. 00000 -  "not a single-group group function"
*Cause:    
*Action:
Error at Line: 7 Column: 7

Question:

So, how do I do it?

like image 845
Xonatron Avatar asked Dec 15 '22 22:12

Xonatron


1 Answers

SELECT username,count(*) from TABLE WHERE username='USERNAME' GROUP BY username

should do the trick!

The reason the first query works is because MySQL can automatically convert that query into an aggregate query, because it "understands" that you want to count all of the rows where username='USERNAME'. The second query isn't clear enough - you're trying to perform an aggregate function on rows selected by the query, but you also want the rows of the query. My query makes it clear that you only expect one username returned out of the set, so aggregation is not a problem.

like image 179
Sean Johnson Avatar answered Feb 23 '23 00:02

Sean Johnson