I need to find the most popular occurrence of an item grouped by date and display the total of all items along with the name of this item. Is something like this possible in a single query?
note: If they are all of equal occurrence (see last 3 rows in Insert) than I can just show at random or the first or last occurrence (whichever is easiest).
If this can't be done in the sql then will have to run through the result and sort the data via PHP which seems like it'll be quite messy.
Edit: Sorry, I had the wrong total for '2009'08-04'. It should be 4.
An example of what I need:
+------------+---------------------+-------+ | date | item | total | +------------+---------------------+-------+ | 2009-08-02 | Apple | 5 | | 2009-08-03 | Pear | 2 | | 2009-08-04 | Peach | 4 | | 2009-08-05 | Apple | 1 | | 2009-08-06 | Apple | 3 | +------------+---------------------+-------+
Here's an example table:
CREATE TABLE IF NOT EXISTS `test_popularity` ( `date` datetime NOT NULL, `item` varchar(256) NOT NULL, `item_id` int(11) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; INSERT INTO `test_popularity` (`date`, `item`, `item_id`) VALUES ('2009-08-02 00:00:00', 'Apple', 1), ('2009-08-02 00:00:00', 'Pear', 3), ('2009-08-02 00:00:00', 'Apple', 1), ('2009-08-02 00:00:00', 'Apple', 1), ('2009-08-02 00:00:00', 'Pear', 0), ('2009-08-03 00:00:00', 'Pear', 3), ('2009-08-03 00:00:00', 'Peach', 2), ('2009-08-04 00:00:00', 'Apple', 1), ('2009-08-04 00:00:00', 'Peach', 2), ('2009-08-04 00:00:00', 'Peach', 2), ('2009-08-04 00:00:00', 'Pear', 3), ('2009-08-05 00:00:00', 'Apple', 1), ('2009-08-06 00:00:00', 'Apple', 1), ('2009-08-06 00:00:00', 'Peach', 2), ('2009-08-06 00:00:00', 'Pear', 3);