2017-02-10 32 views
1

我在SQL Server 2012下表消除重复。结果应该是这样的:SQL服务器:</p> <p><a href="https://i.stack.imgur.com/ZInN5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZInN5.png" alt="enter image description here"></a></p> <p>,我需要选择不同的行,只有其联系等于“自己”:基于两列

enter image description here

我尝试以下查询:

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 

我不知道,如果它可以像使用临时表或where子句不同的方法来实现。

回答

1

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

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表达的ORDER BY条款,明确检查一个叫做“自己的”接触。我们可以尝试使用MIN()MAX(),并依赖于具有NULL的非匹配记录,但如果您的表除了“Own”之外还有其他联系值,则可能会导致问题发生。

0

这where子句应该给你什么你期待

Select DISTINCT SiteAdd from table where Contact = 'Own' 

你可以把不同的整个行上也,万一有重复的行。

Select DISTINCT * from table where Contact = 'Own' 

您的原始查询将基于逻辑工作。只要改变错字:

wehre RN = 1到RN = 1

希望它能帮助。

+0

如果我包含contact ='Own'的地方,我不会回到第2行(SiteNum 2)。 – user2536008

相关问题

 相关问题