查询以计算Mysql中连续行中的距离(经度,纬度)之和 [英] Query to calculate sum of distance (longitude, latitude) in consecutive rows in Mysql

查看:76
本文介绍了查询以计算Mysql中连续行中的距离(经度,纬度)之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对sql还是很陌生,被卡住了.我正在尝试计算每个用户旅行的(每年)距离总和.我有一个具有以下结构的表(我们称其为dist_table):

I am very new to sql and I am stuck. I am trying to calculate the (yearly) sum of distance each user has traveled. I have a table (lets call it dist_table) with the following structure:

rowid     user_name   date             LAT        LONG
1         maria       2005-01-01       51.555     5.014
2         maria       2005-01-01       51.437     5.474
3         peter       2005-02-03       51.437     5.474
4         john        2005-02-03       51.858     5.864
5         maria       2005-02-04       51.858     5.864
6         john        2005-02-03       51.437     5.474
7         john        2006-02-04       0          0
8         john        2006-02-04       51.858     5.864
9         john        2006-02-04       51.858     5.864
10        john        2006-02-04       51.437     5.474

这是计算的中间步骤(只是为了澄清我的意思):

This is the intermediate step in the calculation (just to clarify what I mean):

rowid     user_name   date             LAT        LONG      distance
1         maria       2005-01-01       51.555     5.014     0
2         maria       2005-01-01       51.437     5.474     34.452
3         peter       2005-02-03       51.437     5.474     0
4         john        2005-02-03       51.858     5.864     0
5         maria       2005-02-04       51.858     5.864     54.012
6         john        2005-03-03       51.437     5.474     54.012
7         john        2006-02-04       0          0         
8         john        2006-02-04       51.858     5.864     54.012
9         john        2006-02-04       51.858     5.864     0     
10        john        2006-02-04       51.437     5.474     54.012

这是我需要的最终结果:

And this is the final result I need:

user_name   date       sum(distance)
maria       2005       88.464
peter       2005       0
john        2005       54.012
john        2006       108.024

我当时正在考虑使用此公式(Haversine)计算连续行之间的距离,然后对其求和:

I was thinking of using this formula (Haversine) to calculate the distance between consecutive rows and then summing it up:

SELECT user_name,date,dist_table.LAT,dist_table.LONG, 6373 * 2 * ASIN(SQRT(POWER(SIN((orig_latitude - abs(next_latitude)) * pi()/180 / 2),2)
+ COS(orig_latitude * pi()/180) * COS(abs(next_latitude) * pi()/180) * POWER(SIN((orig_longitude - next_longitude) * pi()/180 / 2),2)  ))
AS distance FROM dist_table WHERE dist_table.LAT !=0 AND dist_table.LONG !=0;

但是,我无法弄清楚如何调用连续的行.到目前为止,这是我试图弄清楚如何连接行时得到的:

However, I am unable to figure out how to call the consecutive row. So far, this is what I got when trying to figure out how to connect the rows:

SELECT user_name, date, LAT,
IFNULL( (
    SELECT MAX( LAT ) 
    FROM dist_table
    WHERE user_name = t1.user_name
    AND ( date < t1.date )
) ,0) AS next_latitude
FROM dist_table AS t1 ORDER BY user_name, date; 

问题在于,对于每个用户,可以有多行满足此条件,并且这将选择最大值而不是前一个.此外,有时经度和/或纬度为0,我需要忽略这些行.

The problem is that for each user, there can be multiple rows satisfying this condition and this chooses the maximum value instead of the previous one. Furthermore, there is sometimes 0 in the longitude and/or latitude and I need to ignore these rows.

如果我先根据user_name和date创建具有行顺序的列,然后在条件中添加date + 1 = t1.date之类的内容,那我可能会解决.不幸的是,我对正在使用的服务器的权限非常有限,因此可能必须使用用户定义的变量来处理,但是我不知道该怎么做.

I was thinking that this could be probably solved, if I first created column with a row order based on user_name and date and then putting something like date+1 = t1.date in the condition. Unfortunately, I have very limited permissions on the server I am using so this would probably have to be handled with user defined variables, but I do not know how to do that.

我正在使用mysql 5.6.19-log.

I am using mysql 5.6.19-log.

有人可以帮我吗?

推荐答案

所以这是问题的第一部分的解决方案...

So here's a solution to the first part of the problem...

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id     INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,user_name   VARCHAR(12) NOT NULL
,date             DATE NOT NULL
,LAT        DECIMAL(5,3) NOT NULL
,LON DECIMAL (5,2) NOT NULL
);

INSERT INTO my_table VALUES
( 1,'maria','2005-01-01',51.555 ,5.014),
( 2,'maria','2005-01-01',51.437 ,5.474),
( 3,'peter','2005-02-03',51.437 ,5.474),
( 4,'john' ,'2005-02-03',51.858 ,5.864),
( 5,'maria','2005-02-04',51.858 ,5.864),
( 6,'john' ,'2005-02-03',51.437 ,5.474),
( 7,'john' ,'2006-02-04',0      ,0),
( 8,'john' ,'2006-02-04',51.858 ,5.864),
( 9,'john' ,'2006-02-04',51.858 ,5.864),
(10,'john' ,'2006-02-04',51.437 ,5.474);


SELECT x.user_name
     , x.id from_id
     , MIN(y.id) to_id
  FROM my_table x
  JOIN my_table y
    ON y.user_name = x.user_name
   AND y.id > x.id
 WHERE (y.lat <> 0 AND y.lon <> 0)
   AND (x.lat <> 0 AND x.lon <> 0)
 GROUP 
    BY x.id;

+-----------+---------+-------+
| user_name | from_id | to_id |
+-----------+---------+-------+
| maria     |       1 |     2 |
| maria     |       2 |     5 |
| john      |       4 |     6 |
| john      |       6 |     8 |
| john      |       8 |     9 |
| john      |       9 |    10 |
+-----------+---------+-------+

对于其余的问题,应执行以下操作.

For the rest of the problem, something like the following should work.

我的数据库中有一个名为geo_distance_km的函数.看起来像这样,并节省了每次键入Haversine公式的时间:

I have a function in my database called geo_distance_km. It looks like this, and saves typing out the haversine formula each time:

delimiter //
create DEFINER = CURRENT_USER function geo_distance_km (lat1 double, lon1 double, lat2 double, lon2 double) returns double
 begin
   declare R int DEFAULT 6372.8;
   declare phi1 double;
   declare phi2 double;
   declare d_phi double;
   declare d_lambda double;
   declare a double;
   declare c double;
   declare d double;
   set phi1 = radians(lat1);
   set phi2 = radians(lat2);
   set d_phi = radians(lat2-lat1);
   set d_lambda = radians(lon2-lon1);
   set a = sin(d_phi/2) * sin(d_phi/2) +
         cos(phi1) * cos(phi2) *
         sin(d_lambda/2) * sin(d_lambda/2);
   set c = 2 * atan2(sqrt(a), sqrt(1-a));
   set d = R * c;
   return d;
   end;
//
delimiter ;

我们可以将其与我们已经拥有的结合起来...

We can combine that with what we have already...

SELECT user_name
     , YEAR(date) year
     , COALESCE(SUM(distance),0) total
  FROM 
     ( SELECT a.*
            , b.lat to_lat
            , b.lon to_lon
            , ROUND(geo_distance_km(from_lat,from_lon,b.lat,b.lon),3) distance
         FROM
            ( SELECT x.user_name
                   , x.date
                   , x.id from_id
                   , x.lat from_lat
                   , x.lon from_lon
                   , MIN(y.id) to_id
                FROM my_table x
                LEFT
                JOIN my_table y
                  ON y.user_name = x.user_name
                 AND y.id > x.id
                 AND (y.lat <> 0 OR y.lon <> 0)
                 WHERE (x.lat <> 0 AND x.lon <> 0)
               GROUP
                  BY x.id
            ) a
         LEFT
         JOIN my_table b
           ON b.id = a.to_id
     ) n
 GROUP
    BY user_name
     , year;

+-----------+------+---------+
| user_name | year | total   |
+-----------+------+---------+
| john      | 2005 | 108.024 |
| john      | 2006 |  54.012 |
| maria     | 2005 |  88.464 |
| peter     | 2005 |   0.000 |
+-----------+------+---------+

我不太了解您如何处理重叠多年的距离,但这应该使您接近所追求的目标.

I don't quite understand how you handle distances that overlap years, but this should get you close to what you're after.

这篇关于查询以计算Mysql中连续行中的距离(经度,纬度)之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆