我在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表或where子句等不同的方法来完成这一任务。
发布于 2017-02-10 17:10:53
我认为您需要按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表达式,它显式地检查一个名为'Own‘的联系人。我们本可以尝试使用MIN()或MAX(),并依赖具有NULL的非匹配记录,但这可能会在以后导致问题,如果您的表除了“自己的”之外还有其他联系人值。
发布于 2017-02-10 17:10:38
这个where子句应该给你你期望的东西。
Select DISTINCT SiteAdd from table where Contact = 'Own'您也可以在整个行上放置不同的信息,以防出现重复的行。
Select DISTINCT * from table where Contact = 'Own'您的原始查询将基于逻辑工作。只需更改错误:
where rn=1 to where rn=1
希望能帮上忙。
https://stackoverflow.com/questions/42164868
复制相似问题