两个表之间的SQL平均值

时间:2017-07-26 09:17:23

标签: sql sql-server join average

我有两张由Computer_ID连接的表。

第一个是Computer_IDCountry,其中包含计算机及其来源国家/地区,第二个表包含有关CPU的信息:Computer_IDCPU_Manufacture

我想为每个国家/地区获取计算机的平均CPU数量

我期待这样的结果:

Country      |Avg CPUs
United-States|2.5
Canada       |3.2

来自Computers表的示例数据:

Computer_ID|Country
1          |United-States
2          |United-States
3          |United-States
4          |United-States
5          |United-States
6          |Canada
7          |Canada

来自CPU表的示例数据: 请注意,每台计算机可以有多个CPU

Computer_ID|CPU_Manufacture
1          |Intel
1          |Intel
2          |Intel
2          |AMD
2          |AMD
3          |AMD
4          |AMD
4          |Intel

任何帮助都会很好。感谢

4 个答案:

答案 0 :(得分:0)

我的第一个问题是:为什么你有这两个表,当你只有一个表时? 根据我收集的内容,您需要这样的查询:

select Country, Avg(Cores)
from computes as t1 left join cpu as t2
on (t1.computer_id = t2.computer_id)
where t2.CPU_Manufacture = 'Intel'
group by Country;

答案 1 :(得分:0)

INNER JOIN您的两个表并使用AVG函数。

SELECT com.Country, AVG(cpu.cores) AS "Avg Cores"
FROM computers com
INNER JOIN cpu on com.Computer_ID = cpu.Computer_ID

答案 2 :(得分:0)

尝试此查询:

SELECT DISTINCT
  t.country,
  t.country_cpu_count / t.country_comp_count AS avg_cpus
FROM
(
  SELECT
    comp.country,
    count(distinct cpu.computer_id) over(partition by comp.country) AS country_comp_count
    count(cpu.cpu_manufacture)      over(partition by comp.country) AS country_cpu_count,
  FROM
    computers comp
  LEFT JOIN
    cpu cpu ON (cpu.computer_id = comp.computer_id)
) t

我希望它会有所帮助。

答案 3 :(得分:0)

您可以使用此解决方案来实现它:

;WITH cte AS (
    SELECT Country,[Computers]=COUNT(*) FROM Computers com
    GROUP BY Country
),
cte2 AS (
    SELECT Country,Cores=COUNT(*) FROM Computers com
    JOIN CPU cpu ON com.Computer_ID=cpu.Computer_ID
    GROUP BY Country
)
SELECT cte.Country,[Cores per computer]=ISNULL(Cores,0)*1./Computers
FROM cte
LEFT JOIN cte2 ON cte.Country=cte2.Country

您没有指定如何处理没有核心的国家/地区,因此我代表每台计算机使用0核心。