2013-11-26 145 views
0

我想從reg_data3的avg_month_val1表中添加平均月份值,但有錯誤查詢無法正常工作。目前的每月平均值不應插入到avg_month_val table.error是具有子句中的未知列名稱。請幫我現在的月份平均值不應該傳遞到平均值表

INSERT IGNORE INTO `clima_data`.`avg_month_val1` ( 
    `year` , `month` , `evep` , `sunshine_hrs` , 
    `rainfall` , `max_temp` , `min_temp`) 
SELECT 
    year(str_to_date(date, '%Y-%m-%d'))as year, 
    month(str_to_date(date, '%Y-%m-%d'))as month, 
    round(avg(evep),2), 
    round(Avg(sunshine_hrs),2), 
    round(sum(rainfall),2), 
    round(AVG(max_temp),2), 
    round(avg(min_temp),2) 
FROM reg_data3 
GROUP BY 
    year(str_to_date(date, '%Y-%m-%d')), 
    month(str_to_date(date, '%Y-%m-%d')) 
HAVING 
    (year(str_to_date(date , '%Y-%m-%d')) <> year(CURRENT_TIMESTAMP) 
    AND month(str_to_date(date , '%Y-%m-%d')) <> month(CURRENT_TIMESTAMP)) 
ORDER BY 1 Desc; 
+0

這個問題沒有答案 – SasinduRHN

回答

0

HAVING只能匹配這是在輸出SELECT'ed列 - 這樣你就可以取代一年()和月()與匹配列部分:

INSERT IGNORE INTO `clima_data`.`avg_month_val1` ( 
    `year` , `month` , `evep` , `sunshine_hrs` , 
    `rainfall` , `max_temp` , `min_temp`) 
SELECT 
    year(str_to_date(date, '%Y-%m-%d'))as year, 
    month(str_to_date(date, '%Y-%m-%d'))as month, 
    round(avg(evep),2), 
    round(Avg(sunshine_hrs),2), 
    round(sum(rainfall),2), 
    round(AVG(max_temp),2), 
    round(avg(min_temp),2) 
FROM reg_data3 
GROUP BY 
    year(str_to_date(date, '%Y-%m-%d')), 
    month(str_to_date(date, '%Y-%m-%d')) 
HAVING 
    (`year` <> year(CURRENT_TIMESTAMP) 
    AND `month` <> month(CURRENT_TIMESTAMP)) 
ORDER BY 1 Desc; 
0

我分組之前將取消不需要的數據,所以處理的行少:

INSERT IGNORE INTO `clima_data`.`avg_month_val1` ( 
    `year` , `month` , `evep` , `sunshine_hrs` , 
    `rainfall` , `max_temp` , `min_temp`) 
SELECT 
    year(str_to_date(date, '%Y-%m-%d'))as year, 
    month(str_to_date(date, '%Y-%m-%d'))as month, 
    round(avg(evep),2), 
    round(Avg(sunshine_hrs),2), 
    round(sum(rainfall),2), 
    round(AVG(max_temp),2), 
    round(avg(min_temp),2) 
FROM reg_data3 
WHERE str_to_date(date, '%Y-%m-%d') < cast(curdate() - 
              day(curdate() - interval 1 day) 
              AS date) 
GROUP BY 
    year(str_to_date(date, '%Y-%m-%d')), 
    month(str_to_date(date, '%Y-%m-%d')) 
ORDER BY 1 Desc; 

而且我會強烈建議改變日期列到真正的日期列,以防止轉化str迄今爲止。因爲如果處理很多行,這消耗了大量的處理能力。