您可以在 SQL Server 中使用DISTINCT来仅获取不同的记录。除此之外,您还可以使用ROW_NUMBER (Transact-SQL)函数通过将数字分配给结果集来获得不同的结果。
的语法row_number()
如下所示。
ROW_NUMBER ( )
OVER ( [ PARTITION BY value_expression , ... [ n ] ] order_by_clause )
下面是实现。
Create table TempTable (name varchar(50), surname varchar(50))
Insert into TempTable Values
('John', 'John')
, ('John', 'John')
, ('Jessica', 'Madson')
, ('Jessica', 'Madson')
, ('Suraj', 'Kumar')
, ('Peter', 'Smith')
Select * from TempTable -- All records.
Select * from(
SELECT name
,surname
,row_number() over (partition by name, surname order by name, surname) as RN -- For partition
FROM TempTable
WHERE name LIKE '%j%' OR surname LIKE '%j%'
)temp
where RN = 1 -- For Distinct records only
输出将如下所示:
您可以在 - db<>fiddle找到演示