2013-11-26 101 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迄今为止。因为如果处理很多行,这消耗了大量的处理能力。