0

I need a MySql query to do the following: Select all the items in a table, group them by a type, order them by count type and also sum all the count.

This is what I've done so far:

select type, count(*) as cnt from $tbl_name group by type order by count(*) desc;

This only gives me the count for each group. What should I add so that this code will also show the total count (sum the counts from every group).

2 Answers 2

1
select * from (
select type as type, 
count(*) as cnt 
from $tbl_name 
group by type WITH ROLLUP) as inner_table
order by cnt desc;

Note that the first row will be the rolled up total sum.

ROLLUP reference

Sign up to request clarification or add additional context in comments.

6 Comments

And how do I acces the value?
Sorry I edited the select cause it threw "incorrect usage of ROLLUP and ORDER BY". With what value do you have problem accessing it?
This query returns: Parse error: syntax error, unexpected T_VARIABLE
@Cristy, there is no T_VARIABLE in this query. I just run it (replaced table name and column name) in my MySQL db and it is just fine.
Sorry my bad, it works ok, but I still don't know how to get the total sum from it. Can you explain that? I mean, I get the cnt by fetching the result and accessing $row['cnt'] , but how do I get the total sum? (inner_table)
|
0

Try this:

select type, SUM(count(*)) as cnt from $tbl_name group by type order by count(*) desc;

3 Comments

I need to have the cnt I've done before and also a variable showing how many items are in total.
if you fetch the query into loop, you can do it there.
I don't do it, I only fetch the first 6 rows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.