質問

I have table with weather statistics eg:

----------------------
| day | temp | falls |
|-----|------|-------|
|  1  |  12  |   30  |
|  2  |  18  |    0  |
|  3  |  13  |   10  |
----------------------

and I want to find day, which is most similar:

Today: 14°C, 0mm falls
Most similar day: 3

Is this possible to achieve it in MySQL only?

役に立ちましたか?

解決

You can check absolute differences between both factors, add them, and search for the lowest sum possible.

But You need to define similar more precisely.

Let's say temperature is twice more important than falls, you'll give a factor 2 to temp, and a factor 1 to falls. Then use this kind of query :

SELECT day 
FROM weather 
ORDER BY (
    2 * ABS(temp - 14) 
  + 1 * ABS(falls - 0)
) ASC
LIMIT 1

他のヒント

I am assuming "similar" refers to similar temperature and similar falls.

 SELECT day FROM weather ORDER BY ABS(temp - 14) + .2 * ABS(falls - 0) LIMIT 1

Though ABS(temp - 14) + .2 * ABS(falls - 0) can be adjusted. Hear, the difference in falls (mm) is weighted less than the difference in temp (C).

For example, if we instead used ABS(temp - 14) + ABS(falls - 0), day two would be chosen.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top