Question

Here is a really strange one guys, at least to me anyways.

I have a query which retrieves some stats for the top few entities and their associated record counts over the last few months.

All works fine however it is not displaying Junes results. The query is running fine it just wont give Junes results.

If I do any of the following then things start to work again:

  1. Change the IN clause to a join instead with a sub query which returns the exact same list as is used by the IN clause
  2. Add the week number to the group by which should be unnecessary as I have checked and the MonthNumber is correctly resolved for the records.

But I really want to find out why this is happening rather than just patching the query. To my eyes here the query I have should work.

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
Was it helpful?

Solution

YEAR() is not an aggregate function and shoult not be use for HAVING clause it should be like instead:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top