0

为什么此查询不返回 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;
4

3 回答 3

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
于 2012-07-16T06:27:40.567 回答
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; 
于 2012-07-16T06:08:27.477 回答
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;
于 2012-07-16T06:08:46.813 回答