Mysql 选择查询算法计算
我想用select查询进行一些基本计算。 我有一个名为“距离”的表,其中有一个属性“保存的距离”。 我想计算Customer1的距离/Customer1、Customer2和Customer3的距离之和。 这种查询形式正确吗:Mysql 选择查询算法计算,mysql,sql,join,division,Mysql,Sql,Join,Division,我想用select查询进行一些基本计算。 我有一个名为“距离”的表,其中有一个属性“保存的距离”。 我想计算Customer1的距离/Customer1、Customer2和Customer3的距离之和。 这种查询形式正确吗: select ((select Distances.distance from Distances where Distances.CustomerID='1') / (select SUM (Distances.distance) fr
select ((select Distances.distance from Distances
where Distances.CustomerID='1') /
(select SUM (Distances.distance) from Distances
where Distances.CustomerID IN ('1', '2', '3')) as ...
我想你只需要使用两次距离表
select cust1.Distance / sum(allCusts.distance)
from distances cust1
cross join distances allCusts
where cust1.CustomerID = '1'
and allCusts.CustomerID in ('1','2','3')
group by cust1.Distance
只需使用条件聚合:
select max(case when d.CustomerID = '1' then d.distance
end) as Cust1Distance,
sum(case when d.CustomerId in ('1', '2', '3') then d.distance
end) as Cust123Distance
from distances d;
如果您只查看这三个客户,那么在('1','2','3')中添加其中的d.CustomerId
应该会提高查询效率