开发者

MySQL and average of multiple columns

I need to return average for each of 12 columns I have in a table in DB. MySQL allows one to get average for one column only. The following query (for one column) works:

SELECT station_id, AVG(jan) AS avg_jan
FROM开发者_运维问答 `climate_data`

WHERE element_name = "Temp_mean_mly" AND jan <> -999999  
GROUP BY station_id 

and the following (for multiple columns) does not (I get syntax error):

SELECT station_id, AVG(jan) AS avg_jan, AVG(feb) AS avg_feb, ... , 
AVG(dec) AS avg_dec 
FROM `climate_data`

WHERE element_name = "Temp_mean_mly" 
AND jan <> -999999 
AND feb <> -999999
AND ... 
AND dec <> -999999 
GROUP BY station_id 

Do I have to use 12 sub-queries to achieve the result I need?


1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'dec)

dec is a reserved MySQL keyword; changing it to `dec` in your query would probably fix that error for you :).

Edit: note that you're also using it in the WHERE clause; it might work there (as it's unlogical for MySQL to find a keyword there), but keep it in mind that you might also have to escape that one :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜