StudioTime
StudioTime

Reputation: 23979

SQL group by and order by issue

Lets say I have a table - tasks - with the following data:

task    user     when_added
---------------------------
run     1        2012-08-09
walk    2        2012-08-07
bike    2        2012-08-07
car     1        2012-08-06
run     2        2012-08-06
car     1        2012-08-05
bike    1        2012-08-04
run     1        2012-08-04

As you can see the task is repetitive.

Question is, when i show the data e.g.

select * from tasks group by task order by when_added desc

How does the group by affecting the results? Does 'group by' group them in any order, can I make it?

The reason i ask is that I have a large table which i show data as above and if I lose the group by and just show results in date order, I get some results which do not show on group by, which means the task has been done before but it seems to be grouping by the oldest date and i want the newest date at the top of the pile.

Hope this makes sense...is it possible to affect the group by order?

Upvotes: 0

Views: 115

Answers (1)

juergen d
juergen d

Reputation: 204756

Is that what you want?

select task, group_concat(user), max(when_added)
from tasks 
group by task
order by when_added desc

group by is an aggregate function. In MySQL you can select not aggregates columns anyway, but you should not do that.

If you group by a column then the results will be distinct for that column and all other data will be grouped around it. So there might be multiple data where task is run for instance. Just selecting other columns will select a random result. You should pick a specific result from that group like max or min or sum or concatenate them.

Upvotes: 1

Related Questions