Sql Query无法正常工作?

时间:2012-07-16 06:04:30

标签: mysql sql

为什么这个查询没有返回2011年和2012年的数据。任何人都可以帮助我。谢谢提前。

SELECT 
    country_code,
    SUM(`attendance`) as k6_attendance,
    count(*) as total_events ,
    IF(MONTH(`session_date`)<5,YEAR(`session_date`),YEAR(`session_date`)+1) as YR2
  FROM `v_knowledge_session` v
  WHERE  session_date >0 
  Group by YR2,country_code
  HAVING YR2>(YEAR(NOW())-2) AND country_code='IN'
  ORDER BY country_code,YR2;

3 个答案:

答案 0 :(得分:1)

尝试将其包装在子选择中,然后在外部查询中对YR2进行比较:

SELECT a.* 
FROM
(
    SELECT 
        country_code,
        SUM(attendance) AS k6_attendance,
        COUNT(*) AS total_events,
        IF(MONTH(session_date)<5,YEAR(session_date),YEAR(session_date)+1) AS YR2
    FROM v_knowledge_session v
    WHERE session_date > 0 AND country_code = 'IN'
    GROUP BY YR2, country_code
) a
WHERE 
    a.YR2 > YEAR(NOW())-2
ORDER BY 
    a.country_code, a.YR2

答案 1 :(得分:0)

您需要在ORDER BY子句以外的其他位置使用相同的表达式

SELECT country_code,SUM(`attendance`) as k6_attendance,count(*) as total_events , 
    IF(MONTH(`session_date`)<5,YEAR(`session_date`),YEAR(`session_date`)+1) as YR2 
    FROM `v_knowledge_session` v 
    WHERE  session_date >0  
    Group by IF(MONTH(`session_date`)<5,YEAR(`session_date`),YEAR(`session_date`)+1) ,country_code 
    HAVING IF(MONTH(`session_date`)<5,YEAR(`session_date`),YEAR(`session_date`)+1) >(YEAR(NOW())-2) AND country_code='IN' 
    ORDER BY country_code,YR2; 

答案 2 :(得分:0)

您不能在HAVING子句中使用非聚合条件。 country_code='IN'必须在WHERE子句中。创建HAVING子句的原因是WHERE子句无法处理聚合条件。在您的查询中,不需要having子句,因为您的条件未汇总。您也可以删除ALIAS v

试试这个:

SELECT    country_code, 
          SUM(`attendance`) as k6_attendance,
          count(*) as total_events ,
          IF(MONTH(`session_date`) < 5 ,
               YEAR(`session_date`),
               YEAR(`session_date`) + 1) as YR2
FROM      `v_knowledge_session` 
WHERE      session_date > 0 AND country_code='IN' AND YR2 > (YEAR(NOW())-2) 
Group by  YR2, country_code
ORDER BY  country_code,YR2;