posts - 495,comments - 227,trackbacks - 0

          我們經(jīng)常會有這樣的需求,即按照地區(qū)來分別取出每個地區(qū)排名前3的那些記錄。本文總結(jié)了幾種方法,希望大家補充。

           

          首先,創(chuàng)建測試用的表和數(shù)據(jù),如下:

           

          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

           

          第一種方法適用于sql2000和2005,其代碼如下:

           

          select * from test a

          where checksum(*) in (select top 3 checksum(*) from test b where a.areaid=b.areaid order by score desc)

           

          第二種方法是利用sql2005的函數(shù)ROW_NUMBER,其代碼如下:

           

          WITH test1 AS

          (

              SELECT *,

              ROW_NUMBER() OVER (PARTITION BY areaid ORDER BY score desc) AS 'RowNumber'

              FROM test

          )

          SELECT *

          FROM test1

          WHERE RowNumber BETWEEN 1 AND 3;

           

          第三種方法是利用sql2005的cross apply來實現(xiàn),其代碼如下:

           

          select distinct t.* from test a

          cross apply

          (select top 3 areaid,score from test

          where a.areaid=areaid order by score desc) as T

          posted on 2012-06-07 15:12 SIMONE 閱讀(505) 評論(0)  編輯  收藏 所屬分類: SQL SERVER
          主站蜘蛛池模板: 平安县| 沧源| 彭州市| 哈尔滨市| 台安县| 社会| 民县| 西乌| 增城市| 闻喜县| 德州市| 双流县| 平武县| 井陉县| 香河县| 宝鸡市| 孟连| 贵阳市| 合川市| 来宾市| 巨野县| 海林市| 大埔区| 罗甸县| 平潭县| 城口县| 闵行区| 中江县| 龙井市| 中宁县| 漳州市| 永年县| 宁国市| 台中县| 铅山县| 资源县| 玉屏| 肇源县| 合江县| 凤翔县| 元朗区|