简体   繁体   中英

MySQL - finding difference between any two integers in same column

I have data concerning prices of goods at various latitudes and longitudes. I am look to find profit opportunities by comparing differences in price with the distance needed to travel to obtain the better prices. The pseudocoded formula looks like this currently:

select (100*diff(avg(price))-50*diff(lon)-70*diff(lat)) as profit

As such, I wish to find the difference between any two latitude values in the data set. I have seen responses that explain how to find the differences between consecutive values or differences in dates, but nothing that seems to address my particular question.

Edit with my current query (this should simply provide me with the two most distant cities latitude wise in descending order): SELECT lat AS lat2, (lat2 - lat) AS latdistance, city FROM buying INNER JOIN buying ON (lat2 = lat) Order by latdistanceasc

The output should list both cities involved as each one contributes a latitude although I am unsure of how to make them both display in the output.

Imagine 3 data points with (Price, Latitude, Longitude): A (10, 30, 50) B (15, 50, 60) C (5, 20, 30)

What is the latitudinal distance between any two points (to keep things simple)? The output should be:

AB - 20 AC - 10 BC - 30

This query works for your conditions:

SELECT b1.city start,
       b2.city finish,
       abs(b1.latitude - b2.latitude) latdistance
FROM buying b1, buying b2
WHERE b1.city < b2.city
ORDER BY 3

You should be warned however, that it is expensive and it will grow number of rows as O(n^2) .

To use better metric for distance, use this:

SELECT b1.city start,
       b2.city finish,
       sqrt(pow(b1.latitude  - b2.latitude,  2)
          + pow(b1.longitude - b2.longitude, 2)) latdistance
FROM buying b1, buying b2
WHERE b1.city < b2.city
ORDER BY 3

Both queries at SQLFiddle .

To compare the current location to all other cities and showing the profit:

SELECT
    here.city AS Here,
    there.city AS There,
    here.price - there.price AS Profit,
    ABS(here.lat - there.lat) AS Distance
FROM buying AS here
-- Join to the table itself, but not to the same city
LEFT JOIN buying AS there ON (here.city <> there.city)
-- Remove this to compare all cities to every other city
WHERE here.city = 'Springfield'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM