SQL queries the first few/specified number of groups

Source: Internet
Author: User

Note: Under sqlserver

Create Table Test

(

Areaid int,

Score int

)

Insert into test select 0, 10

Union all select 0, 20

Union all select 0, 30

Union all select 0, 40

Union all select 0, 50

Union all select 1, 10

Union all select 1, 20

Union all select 1, 30

Union all select 1, 40

Union all select 1, 50

Union all select 2, 10

Union all select 2, 20

Union all select 2,30

Union all select 2,40

Union all select 2,50

Go

Select * from test

-- The first method is applicable to SQL2000 AND ITSCodeAs follows:

Select * from test

Where checksum (*) in (select top 3 checksum (*) from Test B where a. areaid = B. areaid order by score DESC)

-- The second method is to use the sql2005 function row_number. The Code is as follows:

(1)

With test1

(

Select *,

Row_number () over (partition by areaid order by score DESC) as 'rownumber'

From Test

)

Select *

From test1

Where rownumber between 1 and 3;

(2)

Select areaid, score from (

Select *, row_number () over (partition by areaid order by areaid DESC) row_number from test) A where row_number <6 and row_number> 2

-- The third method is to use sql2005's cross apply. The Code is as follows:

Select distinct T. * from test

Cross apply

(Select top 3 areaid, score from test

Where a. areaid = areaid order by score DESC) as t

 

 

SQL retrieves the first row of data for each group

Select a. * From Table1 a inner join (
Select max (a + B) Time from Table1
Group by c) B
On a. A + A. B = B. Time

 

Of course, the row_number in sql2005 provides a variety of solutions to many problems:

Select * from (select T. *, rank ()
Over (partition by T. A order by T. B DESC) as drank
From Table1 t) A where drank = 1

 

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.