【问题标题】:Calculating distance (pythagoras) and running count in sql query在sql查询中计算距离(毕达哥拉斯)和运行计数
【发布时间】:2014-01-08 11:14:24
【问题描述】:

我正在尝试在 SQL 中构建一个相当复杂的查询,作为初学者,我非常感谢构建它的一些帮助。

我正在努力实现以下目标:

1/ 使用笛卡尔纬度和经度坐标,使用毕达哥拉斯计算 target_postcodes 表中的邮政编码(例如 E1 1AA)和 population_postcodes 表中的所有邮政编码之间的distance

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/ 从最近的邮政编码开始,将人口列中的值添加到 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 表中循环这个查询。

非常感谢您帮助新手!

【问题讨论】:

  • 这是 SQL Server,但它可能会给你一些想法blogs.lessthandot.com/index.php/DataMgmt/DataDesign/…
  • 您使用 MS Access 还是 MySQL 作为数据库?
  • 我正在使用 Access,但我认为 sql 查询会相似?
  • 它不会足够相似,例如,当前答案不会在 MS Access 中运行。除非您想要 MySQL 答案,否则最好删除 MySQL 标记。
  • 您能告诉我它有何不同/我如何更正查询吗?

标签: mysql sql database ms-access geolocation


【解决方案1】:

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 点之二。以按 column_name asc/desc 排序结束 http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html

第 3 点。将所有内容写为sub-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 ...

http://dev.mysql.com/doc/refman/5.1/en/create-table.html

【讨论】:

  • 阿德里安非常感谢,我会尝试实现这一点,并让你知道一点。再次感谢您!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多