开发者

SQL query in MySQL using GROUP BY

开发者 https://www.devze.com 2022-12-14 09:43 出处:网络
Okay so this query should be easy but I\'m开发者_如何转开发 having a bit of difficult. Let\'s say I have a table called \'foo\' with columns \'a\', \'b\'.

Okay so this query should be easy but I'm开发者_如何转开发 having a bit of difficult. Let's say I have a table called 'foo' with columns 'a', 'b'.

I'm trying to figure out the following in one query:

select how of column 'a' are available of type column 'b', this is done with the following:

mysql> select count(a),b from foo GROUP BY b;

that's straight forward. but now I want to add a third output to that query as well which shows the percentage of the result from count(a) divided by count(*). So if I have 100 rows total, and one of the GROUP BY results comes back with 20, I can get the third column to output 20%. Meaning that column a makes for 20% of the aggregate pool.


Assuming you have > 0 rows in foo

SELECT count(a), b, (count(a) / (SELECT count(*) FROM foo)) * 100
FROM foo
GROUP BY b


There is a risk of it running slow, best bet is to program whatever is to preform two separate queries.

SELECT count(*) INTO @c FROM foo;
SELECT count(a), b, (count(a)/@c)*100 FROM foo GROUP by b;
0

精彩评论

暂无评论...
验证码 换一张
取 消