选择SQL查询时双重结果

时间:2017-02-22 09:04:42

标签: sql sql-server

我试图通过自己解决这个问题,但我找不到任何解决方案,所以也许你可以提供帮助。我有以下查询:

select users.name,users.userid,position,department.name,num,phone.pname,objpict.fname 
from users 
inner join opict on opict.ownerid=users.id 
inner join department on department.id=users.deptid
inner join phone on phone.ownerid=users.id 
where quitted=0 and tag='web' and opict.del=0 and phone.del=0 and phone.ownertype=5

它工作得很好,但问题是有些用户有2或3个不同的数字,所以选择resoult将是:

Name     UserID   Number
------   ------   --------
David    Test     12345678
David    Test     11111111

所以问题是输出会加倍。我该如何解决它的格式如下:

Name     UserID   Number
------   ------   --------
David    Test     12345678
         Test     11111111

1 个答案:

答案 0 :(得分:2)

如果您不想显示重复值,可以使用ROW_NUMBER()以及CASE声明:

select case
           when row_number() over (partition by users.userId order by users.userId) = 1
               then users.name
           else NULL
        end as userName
    , users.userid
    , position
    , department.name
    , num
    , phone.pname
    , objpict.fname
from users
inner join opict
    on opict.ownerid = users.id
inner join department
    on department.id = users.deptid
inner join phone
    on phone.ownerid = users.id
where quitted = 0
    and tag = 'web'
    and opict.del = 0
    and phone.del = 0
    and phone.ownertype = 5

如果您不希望NULL显示并想要一个"空格"您可以将CASE语句的第二个分支更改为else ''