MS SQL 2005中ROW_NUMBER()OVER関数の使い方

7510 ワード

プロジェクトのsql文ソース:
select top 5 *, ROW_NUMBER() OVER( order by LastUpdTime desc,id) as RowNumber from (select LastUpdTime'C'+convert(varchar(5),c.c_id) as id, shop.Shop_ID,shop.Shop_TEL,f.f_no,shop.Shop_storeys,shop.shop_mng,c.Pledge,c.LivingRoom,c.KitchenRoom,c.Bathroom,shop.title,shop.xiaoqu,shop.Shop_Name,c.LastUpdTime,shop.city,isnull(shop.area,'')+isnull(shop.domtom,'')as addr,c.Room_count,c.c_size,c.c_small,c.C_MODE,c.fitment,c.CToward,shop.elevator,c.Source_,c.c_type,c.rent,c.C_Price,c.Config,c.C_memo,(select top 1 p.Addr from Shop_Union_Photo p where shop.Shop_ID=p.Parent_id)as 'ImgAddr',shop.XPOS_ID,''as woshi from Shop_Union shop,Shop_Union_Floor F,Shop_Union_Class c where shop.Shop_ID=F.Shop_ID and F.F_ID=c.F_ID and c.C_ID not in(select C_ID from Shop_Union_Room) and c.Shelves=1 and c_type in('1','2','3') union all select 'R'+convert(varchar(5),r.r_id) as id, shop.Shop_ID,shop.Shop_TEL,f.f_no,shop.Shop_storeys,shop.shop_mng,c.Pledge,c.LivingRoom,c.KitchenRoom,c.Bathroom,shop.title,shop.xiaoqu,shop.Shop_Name,c.LastUpdTime,shop.city,isnull(shop.area,'')+isnull(shop.domtom,'')as addr,c.Room_count,c.c_size,c.c_small,c.C_MODE,c.fitment,c.CToward,shop.elevator,c.Source_,c.c_type,c.rent,c.C_Price,c.Config,c.C_memo,(select top 1 p.Addr from Shop_Union_Photo p where shop.Shop_ID=p.Parent_id)as 'ImgAddr',shop.XPOS_ID,r.woshi from Shop_Union shop,Shop_Union_Floor F,Shop_Union_Class c,Shop_Union_Room r where shop.Shop_ID=F.Shop_ID and F.F_ID=c.F_ID and c.C_ID=r.C_ID and c.Shelves=1 and c_type in('1','2','3'))as a where 1=1 and a.city='   ' order by newid()

select top  20  *, ROW_NUMBER()OVER(order by LastUpdTime desc,id)----これは神馬の場合???
ネット上の資料を見て同僚に言ったので、私ははっと悟った.
引用資料の一言:row_number関数の用途は非常に広く,この関数の機能はクエリされた各行のレコードにシーケンス番号を生成することである.
OK、それだけで簡単で、クエリーの結果にシーケンス番号を生成します.
row_を使用していますnumber関数は、over句選択を使用してカラムをソートしてからシーケンス番号を生成します.
元SQL文:select row_number() over(order by field2 desc) as row_number,* from t_table order by field1 desc
などなど.元のsql文のover句はorder by field 2 descですが、私のプロジェクトのover句はorder by LastUpdTime desc,id,「,id」は神馬の意味ですか???
同僚が最初に言ったのは、更新時間に基づいて降順に並べ、id昇順に並べます.私はその時気絶して、降ったり昇ったりして、これはめちゃくちゃではありませんか?
その後、自分でデータベーステストrowを新規作成しました.number()は、何が起こっているのかやっと分かりました.
元々、更新時間によって降順に並び、更新時間が同じならid昇順に並びます!
Fuc_!穴があいたような感じがします.
資料の参考と:1.http://www.cnblogs.com/icebutterfly/archive/2009/08/05/1539657.html
      2. http://blog.csdn.net/zzuyongp/article/details/4164891