如何在表上显示逻辑ID

时间:2014-03-12 05:38:26

标签: c# asp.net sql sql-server sql-server-2008

我有员工表和他们的楼层如下所示:

ID        EmployeeId   EmpName  FloorId       

1           abc123       abc       1      
2           xyz123       xyz       1
3           def123       def       2
4           pqr123       pqr       2

我在地板明智的基础上显示了表的结果,但是在表示2楼员工的时候想要结果这样显示:

  

select * from tblname where FloorId=2

ID        EmployeeId   EmpName  FloorId 

1           def123       def       2
2           pqr123       pqr       2

2 个答案:

答案 0 :(得分:2)

您可以使用ROW_NUMBER()。它返回结果集分区中行的序号,从1开始,每个分区的第一行。

试试这个:

SELECT ROW_NUMBER() OVER(ORDER BY ID) as ID,EmployeeId,EmpName,FloorId 
FROM tableName 
WHERE FloorId=2

结果如下:

ID  EMPLOYEEID  EMPNAME FLOORID
1   def123      def     2
2   pqr123      pqr     2

请参阅SQL Fiddle中的结果。

详细了解ROW_NUMBER() here

答案 1 :(得分:1)

DECLARE  @TableName TABLE 
    ([ID] int, [EmployeeId] varchar(6), [EmpName] varchar(3), [FloorId] int)
;

INSERT INTO @TableName
    ([ID], [EmployeeId], [EmpName], [FloorId])
VALUES
    (1, 'abc123', 'abc', 1),
    (2, 'xyz123', 'xyz', 1),
    (3, 'def123', 'def', 2),
    (4, 'pqr123', 'pqr', 2)
;
;WITH CTE AS
(
select ID,EmployeeId,EmpName,ROW_NUMBER()OVER( ORDER BY ID ) RN,FloorId  from @TableName
)
select * from CTE 
WHERE FLOORid = 2