我有一个看起来像这样的表:
name | surname<br>
John | John<br>
Jessica | Madson<br>
我有这样的查询:
SELECT * FROM table WHERE name LIKE '%j%' OR surname LIKE '%j%'
我得到了什么:
John John
John John
Jessica Madson
我想要的是什么:
John John
Jessica Madson
如何摆脱重复的结果?
答案 0 :(得分:21)
使用DISTINCT
:
SELECT DISTINCT name, surname
FROM yourtable
WHERE name LIKE '%j%' OR surname LIKE '%j%'
答案 1 :(得分:5)
尝试:
SELECT DISTINCT name, surname FROM table WHERE name LIKE '%j%' OR surname LIKE '%j%'
答案 2 :(得分:2)
你也可以使用group by
SELECT name, surname
FROM yourtable
WHERE name LIKE '%j%' OR surname LIKE '%j%'
GROUP BY name, surname
答案 3 :(得分:1)
您可以在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
处找到演示。