sql查询时增加自动编号和分页

查询时加序号  
a:没有主键的情形:

Select   identity(int,1,1)   as   
iid,*   into   #tmp   from   TableName   
Select   *   from   #tmp   
Drop 
  table   #tmp  

b:有主键的情形:

Select   (Select   sum(1)   from   
TableName   where   KeyField   <=   a.KeyField)   as   iid,*   from   
TableName   a  

eg:
select (select sum(1) from user_Admin where 
id<=a.id) as ID,id,displayName from user_Admin a order by a.ID asc



 

SELECT 序号= (SELECT COUNT(客户编号) FROM 客户 AS LiMing                  WHERE LiMing.客户编号<= Chang.客户编号),        客户编号, 公司名称 FROM 客户 AS Chang ORDER BY 1; GO
/* 方法二: 使用SQL Server 2005 独有的RANK() OVER () 语法*/ SELECT RANK() OVER (ORDER BY 客户编号 DESC) AS 序号,          客户编号, 公司名称 FROM 客户; GO
/* 方法三*/ SELECT 序号= COUNT(*), LiMing.客户编号, LiMing.公司名称    FROM 客户 AS LiMing, 客户AS Chang    WHERE LiMing.客户编号>= Chang.客户编号    GROUP BY LiMing.客户编号, LiMing.公司名称    ORDER BY 序号; GO
/* 方法四 建立一个「自动编号」的字段,然后将数据新增至一个区域性暂存数据表, 然后由该区域性暂存数据表中,将数据选取出来,最后删除该区域性暂存数据表 */ SELECT 序号= IDENTITY(INT,1,1), 管道, 程序语言, 讲师, 资历 INTO #LiMing FROM 问券调查一; GO SELECT * FROM #LiMing; GO DROP TABLE #LiMing; GO
/* 方法五 使用 SQL Server 2005 独有的ROW_NUMBER() OVER () 语法 搭配 CTE (一般数据表表达式,就是 WITH 那段语法)选取序号2 ~ 4 的数据 */ WITH 排序后的图书 AS   (SELECT ROW_NUMBER() OVER (ORDER BY 客户编号 DESC) AS 序号,    客户编号, 公司名称    FROM 客户) SELECT * FROM 排序后的图书 WHERE 序号 BETWEEN 2 AND 4; GO

 

------------分页使用---------------------------

 SELECT  RANK() OVER (ORDER BY id asc) AS no,* into #temp FROM Bbs_reply  select * from  #temp where no between 1 and 100 drop table  #temp

-------------------------------序号

给查询出的SQL记录添加序号列,解决方法有以下两种 第一:

 
 

select ROW_NUMBER() OVER (ORDER BY a.字段 ASC) AS XUHAO,a.* from table a1

 
 

(table 为表名,字段为表a中的字段名) 第二:

 
 

select RANK()  OVER (ORDER BY a.字段 ASC) AS XUHAO,a.* from table a1

 
 

(table 为表名,字段为表a中的字段名)

 

猜你喜欢

转载自www.cnblogs.com/lsgsanxiao/p/10878378.html