Sql server 如果多行具有相同的名称值,则返回ID值最高的一行
在上表中,如果我在文本框中输入Andrew,我希望获得Id为no=3的数据。如何操作?对于所有唯一的名称:Sql server 如果多行具有相同的名称值,则返回ID值最高的一行,sql-server,Sql Server,在上表中,如果我在文本框中输入Andrew,我希望获得Id为no=3的数据。如何操作?对于所有唯一的名称: ID Name Address Birthdate 1 Steven NULL 1982-01-23 2 Andrew 2 Katherine St 1979-10-06 3 Andrew 81 South Rd NULL 仅举一例: ;WITH cte AS ( SELECT ID, Name, Address, Birthdate,
ID Name Address Birthdate
1 Steven NULL 1982-01-23
2 Andrew 2 Katherine St 1979-10-06
3 Andrew 81 South Rd NULL
仅举一例:
;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;
对于所有唯一名称:
ID Name Address Birthdate
1 Steven NULL 1982-01-23
2 Andrew 2 Katherine St 1979-10-06
3 Andrew 81 South Rd NULL
仅举一例:
;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;
假设表名为“my_table”。 试试这个:
declare @name varchar(100) = 'Andrew'
select top 1 *
from MyTable
where Name = @name
order by ID desc
关于max函数的更多信息。假设表名为“my_table”。 试试这个:
declare @name varchar(100) = 'Andrew'
select top 1 *
from MyTable
where Name = @name
order by ID desc
有关max函数的更多信息。如果OP想要姓名、地址、生日等,除了ID之外,还需要其他信息,那么您是对的。我读到他只想得到最高的身份证,我的坏。:)如果是这样的话,我会同意你的回答。如果OP想要姓名、地址、生日等,除了身份证之外?你是对的。我读到他只想得到最高的身份证,我的坏。:)那样的话,我同意你的回答。