当前月平均值不应传递到平均表

时间:2013-11-26 14:04:16

标签: mysql

我想从reg_data3向avg_month_val1表中添加平均月值,但是错误查询无法正常工作。目前的月平均值不应该插入avg_month_val table.error是having子句中未知的列名。请帮帮我

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;

2 个答案:

答案 0 :(得分:0)

HAVING只能匹配输出中SELECT的列 - 所以你可以用匹配的列替换year()和month()部分:

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;

答案 1 :(得分: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转换为日期。因为如果你处理很多行,这会消耗很多处理能力。