这是一个非常奇怪的人,至少对我而言。
我有一个查询,可以检索过去几个月中前几个实体及其相关记录数的一些统计数据。
一切正常,但没有显示Junes的结果。查询运行正常,它不会给Junes结果。
如果我执行以下任何操作,那么事情就会重新开始:
但我真的想知道为什么会这样,而不仅仅是修补查询。在我看来,我的查询应该有效。
SELECT
YEAR(FROM_UNIXTIME(mt.`date_created`)) AS 'Year',
MONTH(FROM_UNIXTIME(mt.`date_created`)) AS 'MonthNumber',
MONTHNAME(FROM_UNIXTIME(mt.`date_created`)) AS 'MonthName',
WEEKOFYEAR(FROM_UNIXTIME(mt.`date_created`) ) AS 'Week',
`at`.`group_name`,
COUNT(`mt`.`mt_id_pk`) AS 'record_count'
FROM
`my_table` AS `mt`
INNER JOIN `another_table` AS `at` ON `mt`.`at_id_fk` = `at`.`at_id_pk`
WHERE `at`.`group_name` IN ('something1','something2','something3')
GROUP BY `at`.`group_name`, `MonthNumber`
HAVING `Year` = YEAR(NOW())
ORDER BY `MonthNumber` DESC
答案 0 :(得分:1)
YEAR()不是聚合函数,不应该用于HAVING子句,而应该是:
SELECT
YEAR(FROM_UNIXTIME(mt.`date_created`)) AS 'Year',
MONTH(FROM_UNIXTIME(mt.`date_created`)) AS 'MonthNumber',
MONTHNAME(FROM_UNIXTIME(mt.`date_created`)) AS 'MonthName',
WEEKOFYEAR(FROM_UNIXTIME(mt.`date_created`) ) AS 'Week',
`at`.`group_name`,
COUNT(`mt`.`mt_id_pk`) AS 'record_count'
FROM
`my_table` AS `mt`
INNER JOIN `another_table` AS `at` ON `mt`.`at_id_fk` = `at`.`at_id_pk`
WHERE `at`.`group_name` IN ('something1','something2','something3')
AND YEAR(FROM_UNIXTIME(mt.`date_created`)) = YEAR(NOW())
GROUP BY `at`.`group_name`, `MonthNumber`
ORDER BY `MonthNumber` DESC