简体   繁体   中英

count all values and group by with count

I have this query

SELECT poll_numbers.number_title as totale_stemmen,  
       count(poll_stemmen.number_id) as stem 
FROM poll_stemmen
LEFT JOIN poll_numbers on number_id = poll_numbers.id
group by poll_stemmen.number_id

And the output is like this:

totale_stemmen stem    
name             1    
another          1

But how can i count the total number of stem together? in this result it would be 2.

here is the table layout:

poll_stemmen    
number_id, id

poll_numbers
id, number_title

sample data:

id, number_id
1   2
2   8
3   8
4   8

id, number_title
2   title_1
8   title_2

expected output:
number_title, count_number, total_number
title_1       1             4
title_2       3             4

In most databases, you would just use window functions. But, MySQL doesn't support this.

One method is to use a subquery, either in the from clause or select :

SELECT n.number_title, count(s.number_id) as stem,
       x.total_number
FROM poll_stemmen s LEFT JOIN
     poll_numbers n
     on s.number_id = n.id CROSS JOIN
     (SELECT count(*) as total_number FROM poll_stemmen) x
group by s.number_id;

One advantage of putting the query in the from clause is that you know it will be executed only once.

try this

SELECT PN.`number_title`, count(PS.numberid)  
FROM `poll_stemmen` PS 
LEFT JOIN `poll_numbers` PN on PS.`numberid`=PN.`id` 
GROUP BY(PS.`numberid`)

It will be helpful if you provide table structure as this query will count total stems of same title

You can use your query to get count per number_id and use a sub-query to get overall count:

SELECT number_title, COUNT(*) AS count_number,
       (SELECT COUNT(*)
        FROM poll_stemmen
        WHERE number_id IN (SELECT id FROM poll_numbers)) AS total_number
FROM poll_numbers AS pn
LEFT JOIN poll_stemmen AS ps ON ps.number_id = pn.id
GROUP BY ps.number_id 

Demo here

Try this

SELECT p.number_title as number_title,
        count(p.number_id) as count_number,
        (select count(p1.id) FROM `poll_numbers` p1) as total_number  
FROM `poll_numbers` p group by number_title

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM