如何通过 2 个表获得客户的平均考试?

How to get mean of exams by client with 2 tables?

我知道一点点sql,只是最基础的,现在我需要创建一个分析查询,但还不能这样做。

我的数据库 oracle、客户端和考试中有 2 个表:

我尝试了很多方法来获取客户的考试均值,但还没有成功。4

预期的结果是:

考试 = 13

客户 = 6

13/6= 2.166666666...7

我该怎么做?

你可以试试下面的公式得到结果-

SELECT COUNT(*)/COUNT(DISTINCT id_cliente)
  FROM exams;

如果您的客户还没有参加过任何考试,那么您需要:

SELECT AVG(COUNT(e.nu_ordem)) AS avg_exames_by_client
FROM   cliente c
       LEFT OUTER JOIN exames e
       ON (c.id = e.id_cliente)
GROUP BY c.id;

或:

SELECT (SELECT COUNT(*) FROM exames) / (SELECT COUNT(*) FROM cliente)
         AS avg_exames_by_client
FROM   DUAL;

其中,对于示例数据:

CREATE TABLE cliente (id PRIMARY KEY) AS
SELECT 1 FROM DUAL UNION ALL
SELECT 2 FROM DUAL UNION ALL
SELECT 3 FROM DUAL UNION ALL
SELECT 4 FROM DUAL UNION ALL
SELECT 5 FROM DUAL UNION ALL
SELECT 6 FROM DUAL;

CREATE TABLE exames (nu_ordem PRIMARY KEY, id_cliente) AS
SELECT  1, 1 FROM DUAL UNION ALL
SELECT  2, 5 FROM DUAL UNION ALL
SELECT  3, 5 FROM DUAL UNION ALL
SELECT  4, 2 FROM DUAL UNION ALL
SELECT  5, 6 FROM DUAL UNION ALL
SELECT  6, 1 FROM DUAL UNION ALL
SELECT  7, 1 FROM DUAL UNION ALL
SELECT  8, 4 FROM DUAL UNION ALL
SELECT  9, 5 FROM DUAL UNION ALL
SELECT 10, 3 FROM DUAL UNION ALL
SELECT 11, 6 FROM DUAL UNION ALL
SELECT 12, 2 FROM DUAL UNION ALL
SELECT 13, 1 FROM DUAL;

双输出:

AVG_EXAMES_BY_CLIENT
2.166666666666666667

如果您随后添加了几个客户但没有更多的考试:

INSERT INTO cliente (id)
SELECT 7 FROM DUAL UNION ALL
SELECT 8 FROM DUAL

则平均值为:

AVG_EXAMES_BY_CLIENT
1.625

db<>fiddle here