SQL GROUP By field, select the row record where the most value of the other field is located

Source: Internet
Author: User

Introduction:

Why introduce this problem, in the program encountered such a problem, in a data table, the same aid (Project ID) is added to the data table multiple times, so corresponding to a different time, just want to choose which record to add the earliest time.

Reference: Red and Black Alliance

Data tables used:

The effect you want to achieve:

Explanation: The same ID, added by different people (Name), we picked the lowest value (Val) of the row record.

Here's how:

Method One:

1      Select  from T1 A, 2      (Select as Val   from T1 Group by id) b3      where a.id=b.id and  a.val=b.val

Method Two:

1      Select  from T1 a 2      INNER JOIN3      (Select as from T1 Group by id) b 4      On A.id=b.id and A.val=b.val

Note: Method One and method two function the same, and there is no difference, but where is an implicit link, inner join is an explicit link, where is gradually marginalized.

Method Three:

1      Select  from T1 a 2      where a.val= (selectfromwhere id=a.id)

With the same ID, take the minimum Val value.

Method Four:

1      Select  from  as where NOT EXISTS (selectfromwhere b.val<a.val and b.id=a.id)

Expand: Or Group By field, select the data that appears first:

The effect you want to achieve:

Method:

     Select  from  as where val= (select1fromwhere a.id=b.id)

SQL GROUP By field, select the row record where the most value of the other field is located

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.