Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you count the rows in a SQL query which already used count, group by, and having before?

Tags:

sql

count

For example, using the answer for this question:

How to select all users who made more than 10 submissions "How to select all users who made more than 10 submissions."

select userId
from submission   
group by userId
having count(submissionGuid) > 10

Let's say now I want to know many rows this sql statement outputted. How scalable is the solution for counting the rows of counting the rows?

like image 848
danmine Avatar asked Oct 29 '08 04:10

danmine


People also ask

How do I count rows after GROUP BY in SQL?

To count the number of rows, use the id column which stores unique values (in our example we use COUNT(id) ). Next, use the GROUP BY clause to group records according to columns (the GROUP BY category above). After using GROUP BY to filter records with aggregate functions like COUNT, use the HAVING clause.

Can we use GROUP BY and count together in SQL?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

Can we use count and GROUP BY together?

The use of COUNT() function in conjunction with GROUP BY is useful for characterizing our data under various groupings. A combination of same values (on a column) will be treated as an individual group.

Does count work without GROUP BY?

Using COUNT, without GROUP BY clause will return a total count of a number of rows present in the table. Adding GROUP BY, we can COUNT total occurrences for each unique value present in the column.


3 Answers

Slight error in previously posted example, need an alias for a table name for the subquery:


select count(*) from
  (select userId
   from submission 
   group by userId
   having count(submissionGuid) > 10) t

I'm not sure about scalability, but this is the solution. If this isn't scaling well enough for you, you need to consider major design changes, like perhaps tracking those who submitted more than 10 submissions in a separate table that you update through applications that populate the submissions. Or many other possible solutions.

like image 87
user12861 Avatar answered Oct 14 '22 10:10

user12861


Nested queries:

select count(*) from
  (select userId
   from submission   
   group by userId
   having count(submissionGuid) > 10) n

Edited to incorporate mbrierst's comment about needing an alias (the "n" at the end) for the nested subquery. Oracle does not require this, but SQL Server does. Feel free to add a comment regarding usage on other database platforms.

like image 29
BQ. Avatar answered Oct 14 '22 08:10

BQ.


In SQL Server you could do

select @@ROWCOUNT 

immediately following the query you posted.

like image 37
Dave Neeley Avatar answered Oct 14 '22 09:10

Dave Neeley