SQL AVG on Count

时间:2017-07-26 10:58:52

标签: sql sql-server join count average

我有两张由Computer_ID连接的表。

第一个是Computer_IDBrandCountry,其中包含计算机,品牌及其来源国家。

第二个表包含有关CPU的信息:Computer_IDCPU_Manufacture

请注意,每台计算机可以有多个CPU

我想为每个国家/地区获取其品牌为Dell

的计算机的 Intel CPU平均数量

我期待这样的结果:

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

来自Computers表的示例数据:

Computer_ID|Brand|Country
1          |Dell  |United-States
2          |Lenovo|United-States
3          |Lenovo|United-States
4          |Lenovo|United-States
5          |HP    |United-States
6          |Dell  |Canada
7          |Dell  |Canada

来自CPU表的示例数据:

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

这就是我计算每个国家/地区获得的CPU数量的方式:

SELECT COMPUTERS.NATIVE_COUNTRY, COUNT(*) FROM COMPUTERS
INNER JOIN CPUS ON CPUS.COMPUTER_ID = COMPUTERS.COMPUTER_ID AND CPUS.MANUFACTURE = 'Intel'              
GROUP BY COMPUTERS.NATIVE_COUNTRY;

现在基本上我需要将每个COUNT除以每个国家/地区Dell computers的数量。

3 个答案:

答案 0 :(得分:0)

只需添加一个having子句

SELECT COMPUTERS.NATIVE_COUNTRY, COUNT(*) FROM COMPUTERS INNER JOIN CPUS ON CPUS.COMPUTER_ID = COMPUTERS.COMPUTER_ID AND CPUS.MANUFACTURE = 'Intel' GROUP BY COMPUTERS.NATIVE_COUNTRY HAVING COMPUTERS.BRAND = 'DELL';

答案 1 :(得分:0)

如果我理解正确的话。 。

SELECT c.NATIVE_COUNTRY, COUNT(*),
       AVG(CASE WHEN c.BRAND = 'Dell' THEN 1.0 ELSE 0 END) as dell_avg
FROM COMPUTERS c LEFT JOIN
     CPUS cp
     ON cp.COMPUTER_ID = c.COMPUTER_ID AND cp.MANUFACTURE = 'Intel'              
GROUP BY c.NATIVE_COUNTRY;

答案 2 :(得分:0)

此解决方案应该可以按您的方式工作:

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