Sql server 2012 SQL Server:基于两列消除重复项

Sql server 2012 SQL Server:基于两列消除重复项,sql-server-2012,Sql Server 2012,我在SQL Server 2012中有下表: 我需要选择不同的行,并且只选择其联系人等于“Own”的行。结果应该是这样的: 我尝试了以下查询: with cte as ( select row_number() over (partition by contact order by SiteNum) rn, SiteNum, SiteAdd, Description, Contact from Name ) select *

我在SQL Server 2012中有下表:

我需要选择不同的行,并且只选择其联系人等于“Own”的行。结果应该是这样的:

我尝试了以下查询:

with cte as
(
    select 
        row_number() over (partition by contact order by SiteNum) rn,
        SiteNum, SiteAdd, Description, Contact
    from 
        Name
)
select * 
from cte 
where rn = 1

我不确定是否可以使用不同的方法,如temp table或where子句来完成。这个where子句应该能满足您的期望

Select DISTINCT SiteAdd from table where Contact = 'Own'
如果有重复的行,您也可以将distinct放在整行上

Select DISTINCT * from table where Contact = 'Own'
您的原始查询将基于逻辑工作。只需更改输入错误:

wehre rn=1到其中rn=1


希望能有所帮助。

我认为您需要按
SiteNum
进行分区,并按
联系人进行排序,这与您所做的相反。但除此之外,你的方法似乎是正确的。请尝试以下查询:

with cte as
(
    select row_number() over (partition by SiteNum
        order by case when Contact = 'Own' then 0 else 1 end) rn,
        SiteNum, SiteAdd, Description, Contact
    from Name
)
select * from cte 
where rn = 1

注意,我使用了一个
CASE
表达式来表示
orderby
子句,它显式地检查名为“Own”的联系人。我们本可以尝试使用
MIN()
MAX()
并依赖于具有
NULL
的不匹配记录,但如果您的表具有除“Own”之外的其他联系人值,这可能会导致以后出现问题。

如果我包括where contact=“Own”,我将无法返回第2行(SiteNum 2)。