0

我正在尝试处理以下查询:

    选择 TN.name_type_ne, WEEK(HC.date_check,1) AS date_week, YEAR(HC.date_check) AS date_year,
    SUM(IF(id_check > total_check_week, total_check_week, COUNT(id_check))) 作为 unique_check
    FROM HEALTH_CHECK HC
    左连接 TYPE_NE TN ON(HC.fk_id_type_ne = TN.id_type_ne AND HC.fk_id_ne 为 NULL)
    左连接 CATEGORY_NE CN ON (TN.fk_id_category_ne = CN.id_category_ne)
    WHERE CN.name_category_ne = "R4"
    按 T​​N.name_type_ne、date_week、date_year 分组

似乎它会为下一个选择引发错误:

SUM(IF(id_check > total_check_week, total_check_week, COUNT(id_check))) AS unique_check

我还尝试将其替换为:

SUM(CASE WHEN id_check > total_check_week THEN total_check_week ELSE COUNT(id_check) END) AS unique_check

但我一直有这个 Mysql 错误:

#1111 - Invalid use of group function

查询有什么问题??

4

1 回答 1

0

我终于找到了解决方案。就我而言,我试图在 SUM 中使用聚合函数 (COUNT)。似乎 MySQL 不允许这种做法。

这是一个带有派生表的解决方案:

`SELECT SUM(unique_check) FROM
    (SELECT TN.name_type_ne, WEEK(HC.date_check, 1) 作为 date_week, YEAR(HC.date_check) 作为 date_year,
    CASE WHEN COUNT(id_check) > total_check_week THEN total_check_week ELSE COUNT(id_check) END unique_check
    FROM HEALTH_CHECK HC
    左连接 TYPE_NE TN ON(HC.fk_id_type_ne = TN.id_type_ne AND HC.fk_id_ne 为 NULL)
    左连接 CATEGORY_NE CN ON (TN.fk_id_category_ne = CN.id_category_ne)
    WHERE CN.name_category_ne = "R4"
    GROUP BY TN.name_type_ne, date_week, date_year) As T`   
于 2015-05-29T08:42:44.097 回答