简体   繁体   中英

Get total count as well as group count in mysql

Fiddle example

I'm curious to see if there's other option to get the total count as well as group count in one query.

Is using a sub-query the go-to way of getting this result:

TOTAL   OPTIONS OPTION_COUNT
4       A       3
4       B       1

Table Schema:

CREATE TABLE poll
    (`poll_id` int,`user_id` int,`options` varchar(30))
;

INSERT INTO poll
    (`poll_id`,`user_id`,`options`)
VALUES
    (1,1,'A'),
    (2,2,'A'),
    (3,3,'B'),
    (4,4,'A')
;

Query:

SELECT (SELECT Count(*) AS total FROM poll)AS total
,options,option_count
FROM 
(
  SELECT options,Count(options) AS option_count
  FROM poll
  GROUP BY options
)p
GROUP BY options

There is a way to do it using group by rollup

http://dev.mysql.com/doc/refman/5.0/en/group-by-modifiers.html

SELECT options,Count(options) AS option_count
FROM poll
GROUP BY options
WITH ROLLUP

It won't be possible without sub query but one can write in a different and much simpler way like:

select options,Count(options), (SELECT Count(*) FROM poll) from poll GROUP BY options;

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