2
1

More than 3 years have passed since last update.

メモ:BigQueryで2点間の距離を計算する

Last updated at Posted at 2020-07-10

この記事は

BigQueryで距離系の関数使ったのでメモです。

やりたかったこと

  • ownersというテーブルと、shopsというテーブルがそれぞれ緯度・経度を持っているとします
    • イメージは店舗の場所と、オーナー自宅の場所の距離を出す感じ
  • BigQueryで2点間の距離を取得したかったです

やり方

  • id=100のオーナーの情報を出すとしたらこんな感じです
  • パラメータがlatlngではなく、lnglatの順なのだけ注意
select
  owners.name as owner_name,
  shops.name as shop_name,
  st_distance(
    st_geogpoint(owners.longitude, owners.latitude),
    st_geogpoint(shops.longitude, shops.latitude)
  ) as distance
from
  owners inner join places on owners.id = shops.owner_id
where
  owners.id = 100

実行結果

  • こんな表になります。距離はm。
owner_name shop_name distance
山田オーナー 江戸川支店 123
山田オーナー 世田谷支店 456
山田オーナー 東京支店 789

終わりに

  • この値で集計関数で平均とか出せるので便利です
  • BQひいてはSQLってすごいな(今更)
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1