从一列中获取百分比

时间:2015-07-30 10:27:28

标签: mysql

我想获得每家公司的辛勤工作者百分比,但我不知道如何。例如:

Google - > 66%
微软 - > 33%

基于此DB:

CREATE TABLE a_test
    (id int ,`business` varchar(25),`name` varchar(25) , `hard_worker`  int);
INSERT INTO a_test (id, business, name, hard_worker) 
 VALUES (1, 'Google', 'Tom Rudhot', '1'), 
        (2, 'Microsoft', 'Thomas Carpenter', '0'),
        (3, 'Google', 'Peter Butcher', '1'),
        (4, 'Microsoft', 'Sookie Page', '0'),
        (5, 'Microsoft', 'Roonie Redneck', '1'),
        (6, 'Google', 'Robbyn Stackhouse', '0');

http://www.sqlfiddle.com/#!9/33fed/1

3 个答案:

答案 0 :(得分:2)

试试这个(fiddle)

SELECT
   business,
   100 * count(*)
       / (select count(*) 
          FROM a_test
          where hard_worker = 1)
FROM a_test
where hard_worker = 1
group by business

编辑:

先前的查询返回公司的辛勤工作者与所有辛勤工作者的百分比。

但是你似乎想要对每个公司的所有员工都很努力。这更容易:

SELECT
   business,
   100 * sum(case when hard_worker = 1 then 1 end) -- hard workers
       / count(*) -- all workers
FROM a_test as t1
group by business

根据你的0/1实现,你可以简单地使用

   100 * sum(hard_worker)
       / count(*) -- all workers

答案 1 :(得分:1)

我认为这些sql对你有用。

SELECT * FROM (
SELECT ROUND((Google_count/Google_total_count)* 100,2)  AS Google FROM (
SELECT COUNT(business) AS Google_total_count FROM a_test WHERE business = "Google") AS c,
(SELECT COUNT(business) AS Google_count FROM a_test WHERE hard_worker =1 AND business = "Google")AS d) ma
JOIN
(
SELECT ROUND((Microsoft_count/Microsoft_total_count)* 100,2)  AS microsoft FROM (
SELECT COUNT(business) AS Microsoft_total_count FROM a_test WHERE business = "Microsoft") AS a,

(SELECT COUNT(business) AS Microsoft_count FROM a_test WHERE hard_worker =1 AND business = "Microsoft") AS b) ma1

谢谢

答案 2 :(得分:1)

最简单的方法是(暂时不能测试它,因为sql小提琴似乎失败了)

SELECT business,100 * (sum(hard_worker)/ count(*) )
FROM a_test group by business