Unfortunately, the post that you are looking at is wrong. MySQL documentation explicitly says that group by
chooses arbitrary values for columns when they are not specified in the group by
clause.
Here is the explicit quote from here.
MySQL extends the use of GROUP BY so that the select list can refer to
nonaggregated columns not named in the GROUP BY clause. This means
that the preceding query is legal in MySQL. You can use this feature
to get better performance by avoiding unnecessary column sorting and
grouping. However, this is useful primarily when all values in each
nonaggregated column not named in the GROUP BY are the same for each
group. The server is free to choose any value from each group, so
unless they are the same, the values chosen are indeterminate.
Furthermore, the selection of values from each group cannot be
influenced by adding an ORDER BY clause. Sorting of the result set
occurs after values have been chosen, and ORDER BY does not affect
which values within each group the server chooses.
The correct approach (which is standard SQL) is to calculate the appropriate maximum time stamp and then join the results back in:
SELECT t.*
FROM table_name t join
(select name, year, category, max(timestamp) as maxts
from table_name
WHERE year ='2013' AND category='Network'
group by name, year, category
) tn
on t.name = tn.name and
t.year = tn.year and t.category = tn.category and t.timestamp = tn.maxts
ORDER BY sales_total DESC;
EDIT:
This is your query:
SELECT t.*
FROM annualtable t join
(SELECT year, name, max(countries)
FROM annualtable
WHERE name NOT LIKE '%No Entries%' and year <> '0'
GROUP BY year
ORDER BY year
) tn
on t.name = tn.name and t.year = tn.year t.countries = tn.countries
ORDER BY year DESC;
There are two problems. One is the missing and
before the third clause in the on
. The second is that you need to include name
in the group by
for the subquery. You may have another problem if you expect the order by
to do anything. See the above reference in the documentation. So, you may want this:
SELECT t.*
FROM annualtable t join
(SELECT year, name, max(countries)
FROM annualtable
WHERE name NOT LIKE '%No Entries%' and year <> '0'
GROUP BY year, name
) tn
on t.name = tn.name and t.year = tn.year and t.countries = tn.countries
ORDER BY year DESC;