문제

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