Search code examples
mysqlgroup-bynestedsql-timestamp

MySQL: group by hour AND by other distinct fields


I have a 'logs' table, in which search results' counters are stored, as well the search query and the user who searched for it.

My goal is to display results grouped by hour, but I'm having some issues when using GROUP BY because I'm losing the distinct users / queries in the process.

Here's a fiddle: http://sqlfiddle.com/#!9/484c01/7

As you can see, results are being count according to their results no. but the output is not correct. Thanks in advance for any help.


Solution

  • There are data size limits on what can be returned by the following method, but if you want to preserve distinct row values of non-grouped-by-columns when doing a GROUP BY, you can use the GROUP_CONCAT MySQL function which will combine each row's value into one row separated by something like commas.

    See http://dev.mysql.com/doc/refman/5.6/en/group-by-functions.html#function_group-concat for usage examples.

    IMPORTANT: be sure to read the documentation's note on group_concat_max_len and max_allowed_packet in the link provided above.