我正在尝试处理以下查询:
SELECT 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))) AS unique_check FROM HEALTH_CHECK HC LEFT JOIN TYPE_NE TN ON (HC.fk_id_type_ne = TN.id_type_ne AND HC.fk_id_ne IS NULL) LEFT JOIN 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
似乎它会为下一个选择引发错误:
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
查询有什么问题??
答案 0 :(得分:0)
我终于找到了解决方案。就我而言,我试图在SUM中使用聚合函数(COUNT)。似乎MySQL不允许这种做法。
以下是派生表的解决方案:
`SELECT SUM(unique_check) FROM (SELECT TN.name_type_ne, WEEK( HC.date_check, 1 ) AS date_week, YEAR( HC.date_check ) AS 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 LEFT JOIN TYPE_NE TN ON (HC.fk_id_type_ne = TN.id_type_ne AND HC.fk_id_ne IS NULL) LEFT JOIN 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`