Database ranking SQL, group by group query by maximum time, sqlgroup

Source: Internet
Author: User

Database ranking SQL, group by group query by maximum time, sqlgroup

First, give a simple table similar

Drop table if exists 'toutiaoanchor'; create table 'toutiaoanchor' ('urid' int (10) unsigned not null, 'betintime' varchar (40) not null, 'anchoruid' int (11) unsigned not null, 'ticket' int (10) unsigned not null default '0' comment' shining value', 'pic 'varchar (500) DEFAULT '', 'info' varchar (128) not null, 'start' int (11) not null comment 'Star value', 'hitnum' int (11) not null comment 'number of consecutive hits, accumulative for the last time, otherwise accumulated again ', 'Week 'Int (11) not null comment' week ', 'flag' int (11) not null comment' indicates whether it is used for sorting. 1 indicates ', primary key ('urid') ENGINE = InnoDB default charset = utf8;


Currently, ranking is based on group by. Each ranking is based on the field of the first record in each group,

For example

select AnchorUid,pic,SUM(star)as starNum,BetinTime from  TouTiaoAnchor  GROUP BY AnchorUid  ORDER BY starNum DESC,BetinTime asc LIMIT 0,3

At this time, betintIme is the time of the first record. However, I want to use the time of the latest record.


Therefore, I cannot achieve what I want.

After analysis, group by is the first data. So I will give it to him again.

At this time, we need to use a new table.


select AnchorUid,pic,SUM(star)as starNum,BetinTime from (select * from TouTiaoAnchor ORDER BY BetinTime DESC ) tt GROUP BY AnchorUid  ORDER BY starNum DESC,BetinTime asc LIMIT 0,3

In this way, the problem is solved.




Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.