13

我有一个看起来像这样的表:

name     | surname
------------------
John     |  John
Jessica  |  Madson

我有一个这样的查询:

SELECT *
FROM TABLE
WHERE name LIKE '%j%'
    OR surname LIKE '%j%'

我得到什么:

John John
John John
Jessica Madson

我想要的是:

John John
Jessica Madson

我怎样才能摆脱重复的结果?

4

4 回答 4

26

使用DISTINCT

SELECT DISTINCT name, surname
FROM yourtable
WHERE name LIKE '%j%' OR surname LIKE '%j%'
于 2012-05-18T21:18:58.800 回答
7

尝试:

SELECT DISTINCT name, surname FROM table WHERE name LIKE '%j%' OR surname LIKE '%j%'
于 2012-05-18T21:19:18.213 回答
3

您也可以使用 group by

SELECT name, surname
FROM yourtable
WHERE name LIKE '%j%' OR surname LIKE '%j%'
GROUP BY name, surname
于 2012-05-18T21:26:06.823 回答
2

您可以在 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找到演示

于 2020-02-03T12:16:11.547 回答