Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of grouped rows in mysql when I already count the total rows

I have the below table and I want to do the following:

  1. Count the number of times each item appears in the table

  2. Count the DISTINCT number of items

  3. Group the items by name

    +-------+---------+
    |  id   |  names  |
    +-------+---------+
    |   1   |  Apple  |
    |   2   |  Orange | 
    |   3   |  Grape  | 
    |   4   |  Apple  | 
    |   5   |  Apple  | 
    |   6   |  Orange | 
    |   7   |  Apple  | 
    |   8   |  Grape  |  
    +-------+---------+
    

    For the 1. and 3. points I have the following query which works quite well:

    SELECT * , 
       COUNT(names) as count_name, 
       FROM tbl_products WHERE type = '1' 
       GROUP BY names
    

    So I get:

    Apple  (4)
    Orange (2)
    Grape  (2)
    

Now I want to also count the number of grouped by rows and added a line to count the distinct elements, however there is some problem, since MySQL accepts the query but cannot output a result:

SELECT * , 
   COUNT(names) as count_name, 
   COUNT(DISTINCT names) as count_total 
   FROM tbl_products WHERE type = '1' 
   GROUP BY names

Can anyone advice what might be the problem?

EDIT: For more clearance I want to get a table like this:

    +-------+---------+------------+-------------+
    |  id   |  names  |  count_ctg | count_total |
    +-------+---------+------------+-------------+
    |   1   |  Apple  |      4     |      3      |
    |   2   |  Orange |      2     |      3      |
    |   3   |  Grape  |      2     |      3      |
    +-------+---------+------------+-------------+
like image 996
user3132858 Avatar asked Oct 19 '22 16:10

user3132858


1 Answers

Why not just use the query you are using:

SELECT * , 
COUNT(names) as count_name, 
FROM tbl_products WHERE type = '1' 
GROUP BY names

This query achieves all three objectives.

1) You get a count of the number of each name value in count_name.

2) The number of distinct names values will be equal to the number of rows in the result set , since you are grouping by names. Pretty much any client-side MySQL DB connection library will enable you to retrieve this value.

3) You meet your third criteria of grouping by name by explictly using GROUP BY names

Of course the value for id in the result set is meaningless, you may want to only select names and count_names.

like image 90
Mike Brant Avatar answered Oct 22 '22 18:10

Mike Brant