To compute the average angle in a table (angles in degrees [0, 360]) I use the following statement:
SELECT
(CASE WHEN (a < 0.0)
THEN a + 360.0
ELSE a END) as angle
FROM (
SELECT
degrees(atan2(avg(sin(radians(x))), avg(cos(radians(x))))) as a
FROM
angle_t
) as t
UNION
SELECT
x
FROM
angle_t
when it came to testing I tried my table containing yahoo weather data:
WITH angle_t(x) AS (
SELECT
cast(wind_direction as double precision)
FROM
weather_yahoo
WHERE
time >= current_date - interval '1 days' - interval '1 hours'
AND
time <= current_date - interval '1 days')
The output was:
246.670436944698
250.0
240.0
I wondered why the average angle wasn’t 245 but 246.67… so I ran another test with apparantly equal input data:
WITH angle_t(x) AS (VALUES
(240 :: double precision),
(250))
The output showed the (un-)expected result:
245.0
250.0
240.0
Can anyone explain this to me? (this is PostgreSQL 8.4)
The
UNIONoperator eliminates duplicate entries.From the documentation [emphasis mine]:
Therefore, if
UNION ALLis used, the explanation for the unexpected outcome is obvious: