嵌套SELECT计算两个表的平均值

时间:2018-07-07 11:50:50

标签: mysql sql

我有两个表:

  1. 工作人员-持有员工ID,受雇公司,合同种类(比如说“ a”或“ b”)

    +----+------------+----------+
    | id | company_id | contract |
    +----+------------+----------+
    |  1 |          1 | a        |
    |  2 |          1 | b        |
    |  3 |          3 | b        |
    |  4 |          2 | a        |
    +----+------------+----------+
    
  2. 公司-保存公司ID和公司名称。

    +----+--------------+
    | id | company_name |
    +----+--------------+
    |  1 | Company 1    |
    |  2 | Company 2    |
    |  3 | Company 3    |
    |  4 | Company 4    |
    +----+--------------+
    

我想做的是选择在两种合同中雇用的每个公司的平均雇员数。 这是我写的:

SELECT
  (SELECT COUNT(*)
   FROM Workers
   WHERE `contract` = 'a') / (SELECT COUNT(*)
                                FROM Companies) 'Contract A',
  (SELECT COUNT(*)
   FROM Workers
   WHERE `contract` = 'b') / (SELECT COUNT(*)
                               FROM Companies)  'Contract B';

还有:

SELECT
  sum(case when `contract` = 'a'
    then 1
      else 0 end) / (SELECT COUNT(*)
                     FROM Companies) 'Contract A',
  sum(case when `rodzaj contract` = 'uop'
    then 1
      else 0 end) / (SELECT COUNT(*)
                     FROM Companies) 'Contract B'
FROM Workers;

哪个效率更高?有没有更简单的方法?我正在使用MySQL。

预期输出为合同A-0,5,合同B-0,5,因为这4家公司的合同A中有2个人,而这4家公司的合同B中有2个人

1 个答案:

答案 0 :(得分:2)

我会去

SELECT SUM(contract = 'a') / c.cnt as contract_a,
       SUM(contract = 'b') / c.cnt as contract_b
FROM Workers w CROSS JOIN
     (SELECT COUNT(*) as cnt FROM Companies) c;

或者,如果您可以在单独的行中处理结果:

select contract, count(*) / cnt
from Workers w cross join
     (select count(*) as cnt from Companies) c
group by contract, cnt;

关于性能,将count(*)子句放在FROM子句中可确保只对它进行一次评估。因此,这似乎可以提高性能。

此外,仅对字符串和日期常量使用单引号。尝试使用不需要转义的列别名。