1
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 的数据。怎么做到呢?

4

3 回答 3

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;
于 2013-08-06T13:20:32.140 回答
2
declare @name varchar(100) = 'Andrew'

select top 1 *
from MyTable
where Name = @name
order by ID desc
于 2013-08-06T13:21:10.650 回答
0

假设表名是“my_table”。尝试这个:

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

更多关于这里的 max 函数。

于 2013-08-06T13:25:00.923 回答