查询以获取特定区域内有多少客户的百分比

时间:2018-04-05 09:37:13

标签: mysql sql percentage

我有一个x,y coord客户表,我需要查找某个区域内有多少客户居住的百分比(50,50)

查询测试数据少于50的任何人:

SELECT X_Coord, Y_Coord
from customerlocation
count where (X_Coord < 50 or Y_Coord < 50)
50岁的人:

SELECT X_Coord, Y_Coord
from customerlocation
count where (X_Coord = 50 or Y_Coord = 50)

如何对这些查询进行分组,以获得一定比例(50,50)生活在(50,50)范围内的人?

4 个答案:

答案 0 :(得分:0)

为每项要求单独计算并除以总计数

select (a.count / count(*)) * 100, (b.count / count(*)) * 100
from 
(select count(*) as count
  from customerlocation where x_coord < 50 or y_coord < 50) as a,
(select count(*) as count
  from customerlocation where x_coord = 50 or y_coord = 50) as b,
customerlocation

答案 1 :(得分:0)

的MySQL

计算X,Y坐标值:

Strict markdown style by default

答案 2 :(得分:0)

试试这个。

select
cast(sum(A.lessthan50) as float)/cast((sum(A.lessthan50) + 
sum(A.anyoneat50)) as float)*100 lessthan50, 
cast(sum(A.anyoneat50) as float)/cast((sum(A.lessthan50) + 
sum(A.anyoneat50)) as float)*100 anyoneat50
from
(
select 
case when (x < 50  or y < 50) then 1 else 0 end as lessthan50,
case when (x = 50 or y = 50) then 1 else 0 end as anyoneat50
from cordinates
) A

答案 3 :(得分:0)

我认为这是最简单的方法:

select avg( (X_Coord = 50 or Y_Coord = 50) )
from customerlocation
where X_Coord <= 50 or Y_Coord <= 50;

这看起来有点棘手,所以这里有一个稍微冗长的替代方案:

select sum( (X_Coord = 50 or Y_Coord = 50) ) / sum( (X_Coord < 50 or Y_Coord < 50) )
from customerlocation
where X_Coord <= 50 or Y_Coord <= 50;
相关问题