如果多行具有相同的Name值,则返回ID值最高的行

时间:2013-08-06 13:18:04

标签: sql-server

ID  Name    Address Birthdate

1   Steven  NULL    1982-01-23 

2   Andrew  2 Katherine St  1979-10-06

3   Andrew  81 South Rd NULL

在上表中,如果我在文本框中输入Andrew,我想获取Id no = 3的数据。怎么办呢?

3 个答案:

答案 0 :(得分:2)

对于所有唯一名称:

;WITH cte AS
(
  SELECT ID, Name, Address, Birthdate,
    rn = ROW_NUMBER() OVER (PARTITION BY Name ORDER BY ID DESC)
  FROM dbo.tablename
)
SELECT ID, Name, Address, Birthdate
FROM cte
WHERE rn = 1;

只有一个:

SELECT TOP (1) ID, Name, Address, Birthdate
  FROM dbo.tablename
  WHERE Name = 'Andrew'
  ORDER BY ID DESC;

答案 1 :(得分:2)

declare @name varchar(100) = 'Andrew'

select top 1 *
from MyTable
where Name = @name
order by ID desc

答案 2 :(得分:0)

假设表名是'my_table'。 试试这个:

SELECT max(ID) FROM my_table WHERE Name = 'Andrew'

有关最大函数here的更多信息。