SQL在查询中隐藏重复的地址

时间:2019-06-20 17:28:22

标签: sql sql-server reporting-services

我正在尝试在SQL Server 2008中创建一个邮件列表,我们在其中显示员工的所有地址,但是,许多员工共享相同的地址,并且我们不希望列表中有重复的地址。我当前的查询无法正常工作。

如何隐藏包含重复地址的行?

这是我到目前为止的查询:

SELECT
  empid, 'empfirstname + emplastname', 
  empaddress, empaddress2, empzipcode, empcity,empstate,empcountry
from emp
group by empaddress

这是我目前看到的:

这就是我想要的:

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以使用在大多数数据库管理系统上都可以使用的窗口分析功能row_number()(由于我们尚不了解您)

select *
from
(
select
  name, address, country, ID, -- due to the data on the picture
  row_number() over (partition by address order by id) as rn 
from emp
) q
where rn = 1

答案 1 :(得分:0)

使用“不存在”:

select
  e.empid, e.empfirstname + e.emplastname, 
  e.empaddress, e.empaddress2, e.empzipcode,
  e.empcity, e.empstate, e.empcountry
from emp e
where not exists (
  select 1 from emp
  where id < e.id and empaddress = e.empaddress and empzipcode = e.empzipcode
)

我想empaddressempzipcode足以定义一个不同的地址。