SQL group queries the first few data in each group

Source: Internet
Author: User
Tags getdate

  / * First implementation method, low efficiency and error * /DECLARE @DD DATETIME SET @DD = GETDATE () SELECT a.goodsid, A.account, a.lastupdate from                                            Dbo.tb_app_goods a left JOIN dbo.tb_app_goods b on a.account = B.account    and A.lastupdate > B.lastupdate GROUP by A.goodsid, A.account, A.lastupdate have          COUNT (B.GOODSID) < 2 ORDER by A.account, A.lastupdate DESC; PRINT DATEDIFF (Millisecond, @DD, GETDATE ())/ * The second method of implementation, high efficiency and accurate * /SET @DD = GETDATE () SELECT a.goodsid, A.account, a.lastupdate from Dbo.tb_app_goods as a                                Left JOIN (SELECT row_number () over (PARTITION by account ORDER by Lastupdate DESC) as C, * from Dbo.tb_app_goods) as B on a.goodsid = B.goodsid WH          ERE (B.C between 1 and 2) ORDER by A.account, A.lastupdate DESC; PRINT DATEDIFF (Millisecond, @DD, GETDATE ())

Execution Result:

The second method is obviously the most efficient:

Not only is the efficiency high, look closely, the query results are not the same, the first method results more than the second method query:

Reason:

The first method of what ghost, the query came out is not accurate enough,

Summary: Be sure to use the second method

Hereby record that,

SQL group queries the first few data in each group

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.