SQL Implementation Group queries take the first few records

Source: Internet
Author: User

The function I want to implement is to count the first three records of each order in the Order Log table, with the following table structure:

An order in the Fixed bar log table has more than one record, according to the time to query out the first three records of each order, SQL as follows:

 SelectB.ordernumber,b.creationtime,b.remark from  (    SELECTA.ordernumber,a.creationtime,a.remark from [Fortunelabford].[dbo].[So_log]awhereA.sysidinch        (         Select TOP 3Sysid from [Fortunelabford].[dbo].[So_log]          whereA.ordernumber=So_log.ordernumberORDER  byA.creationtimeDESC)) bGroup  byB.ordernumber,b.creationtime,b.remarkORDER  byB.ordernumber

The idea is: first in the inner layer according to CreationTime do sort, and then self-related to the table, according to the primary Key association, and then the result set grouping and sorting, so that the same order of three records are sorted together

This method of querying applies to fields with unique identities in the table, which cannot be checked if there are no uniquely identified fields.

SQL Implementation Group queries take the first few records

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.