Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 选择查询算法计算_Mysql_Sql_Join_Division - Fatal编程技术网

Mysql 选择查询算法计算

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查询进行一些基本计算。 我有一个名为“距离”的表,其中有一个属性“保存的距离”。 我想计算Customer1的距离/Customer1、Customer2和Customer3的距离之和。 这种查询形式正确吗:

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
应该会提高查询效率