我正在尝试在 SQL 中构建一个相当复杂的查询,作为一个初学者,我将非常感谢一些帮助来构建它。
我正在努力实现以下目标:
1/计算 target_postcodes 表中的邮政编码(比如 E1 1AA)与 population_postcodes 表中的所有邮政编码之间的距离
,使用毕达哥拉斯的笛卡尔纬度和经度坐标:
SQRT( POW(MY_Y_AXIS - Y_AXIS, 2) + POW(MY_X_AXIS-X_AXIS, 2) )
2/使用这些distance
值创建一个新列,
not sure how to do that step
2-bis/根据我们获得的distance
值对population_postcodes
中的邮政编码进行排序,
not sure how to do that step
3/从最近的邮政编码开始,将 population 列中的值添加到 running_count 列 UNTIL running_count
> Number_of_beds
of E1 1AA ,
建议的运行计数查询 - 但缺少上述中断条件:
SELECT distance, Population,
(SELECT sum(population_postcodes.Population)) AS Total
FROM population_postcodes
WHERE population_postcodes.distance <= T1.distance) AS Total
FROM population_postcodes AS T1
4/创建一个新表,其中包含邮政编码 E1 1AA (target_postcode
) 和添加到我们的运行计数中的最后一个邮政编码的距离值。
最后,我需要在整个 target_postcodes
表上循环此查询。
非常感谢您帮助新手!
最佳答案
1., 2. 将表放在一起,并在表之间进行操作,需要使用Join http://dev.mysql.com/doc/refman/5.0/en/join.html 否则你的公式是正确的。要将其创建为查询中的列,只需将其写入投影(选择)部分即可。 示例:
select
population_postcodes.*,
target_postcodes.*,
SQRT( POW(population_postcodes.longitude- target_postcodes.longitude, 2) + POW(population_postcodes.latitude-target_postcodes.latitude, 2) ) as distance
from population_postcodes JOIN target_postcodes
要点 2 之二。以 Order by column_name asc/desc 结尾 http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html
要点3. 把所有东西都写成一个子查询
,在top query中只选择你需要的。另请查看 HAVING
http://dev.mysql.com/doc/refman/5.0/en/subqueries.html
http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html
要点 4. 查看创建表格的方法并应用您所学的知识
create table mytablename
select ... my projection columns
from ...
关于mysql - 在sql查询中计算距离(pythagoras)和运行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20994005/