获得一个城市的客户百分比

时间:2016-02-24 11:17:43

标签: mysql

我想检索居住在某些城市的注册客户的百分比。

目前我有这个

SELECT
COUNT(city) / Count(CustID) * 100 AS percent, city
FROM customer
GROUP BY City

目前每行提供100%的结果 我错过了一些明显的东西。如何修复查询?

2 个答案:

答案 0 :(得分:1)

您需要在单独的子查询中获取客户总数:

SELECT COUNT(city) / (SELECT Count(CustID) FROM Customer) * 100 AS percent, city
FROM customer
GROUP BY City

或使用CROSS JOIN

SELECT
COUNT(city) / x.cnt * 100 AS percent, city
FROM customer
CROSS JOIN (SELECT Count(CustID) AS cnt FROM Customer) AS x
GROUP BY City

答案 1 :(得分:0)

试试这个

SELECT
COUNT(city) / (SELECT Count(CustID) FROM Customer) * 100 AS percent, city
FROM customer c
GROUP BY City