So how do you solve the sorted output of the grouped data according to the DESC of the primary key?
There are two ways of answering:
1, the use of subqueries first sorted the table, and then the Word table for group by query, the resulting column will be the subquery obtained a record of the column.
2. Use the Max function to compare the columns that can calculate the maximum value, this method will only make the contrast column in accordance with DESC output, does not affect the other columns.
The results of these two methods are different and use them on demand.
With examples:
Table TAB1 has 3 columns: primary key ID, name, login time
ID Name time
1 A01 1
2 Www.111cn.net 2
3 A03 3
4 A02 4
5 A01 5
6 A04 6
Demand:
1, request to check out the number of users and the last landing time
Solution:
The first of these methods
Select Sub.name,count (sub.id) as login_nums,sub.time as Last_time
From (SELECT * from TAB1) Sub
GROUP BY Sub.name
Note: At this point, each column that the query obtains belongs to the same row of the original table, such as the ID of the specified query, and the ID of the row record with the latest time 111cn.net
The second method
Select Name,count (ID) as Login_nums,max (time) as Last_time
From TAB1
Group BY name
Note that each column that is being queried at this time is no longer part of the same row as the original table.