Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count total records after groupBy select

I have a mysql select query that has a groupBy. I want to count all the records after the group by statement. Is there a way for this directly from mysql ?

thanks.

like image 309
Gabriel Solomon Avatar asked Apr 23 '10 09:04

Gabriel Solomon


People also ask

How do you COUNT after GROUP BY?

After using GROUP BY to filter records with aggregate functions like COUNT, use the HAVING clause. It's always used after the GROUP BY clause. In HAVING, we use a condition to compare a value with one returned by the aggregate function. In the example, we compare whether COUNT(id) returns a value higher than two.

Can we use COUNT with GROUP BY clause?

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.

How do I COUNT grouped data in SQL?

SQL – count() with Group By clauseThe count() function with the GROUP BY clause is used to count the data which were grouped on a particular attribute of the table.

How can you filter the rows after GROUP BY clause?

After Grouping the data, you can filter the grouped record using HAVING Clause. HAVING Clause returns the grouped records which match the given condition. You can also sort the grouped records using ORDER BY. ORDER BY used after GROUP BY on aggregated column.


1 Answers

If the only thing you need is the count after grouping, and you don't want to use 2 separate queries to find the answer. You can do it with a sub query like so...

select count(*) as `count`
from (
    select 0 as `doesn't matter`
    from `your_table` yt
    group by yt.groupfield
) sq

Note: You have to actually select something in the sub query, but what you select doesn't matter

Note: All temporary tables have to have a named alias, hence the "sq" at the end

like image 180
CobaltBlueDW Avatar answered Oct 09 '22 06:10

CobaltBlueDW