SQL视图一次显示相同的ID

时间:2013-09-11 10:36:05

标签: sql sql-server join view group-by

我有两张表来存储有关人员的信息。一个保存用户名和地址信息,另一个保存与用户ID的外键链接的多个电话号码。现在我想创建一个视图,其中只有我在一行和电话号码栏中显示的用户应该列出链接到该用户的所有电话号码。我尝试过Full Join,它根据用户拥有的电话号码多次给同一个用户。

现在代码看起来像是用于创建视图

  

创建视图StudentData AS       SELECT COALESCE(Students.FirstName +'','')+ COALESCE(Students.LastName,'')AS'Name',       COALESCE(Students.City +',','')+ COALESCE(Students.Country +',','')+ COALESCE(Phone.PhoneType,'')+       COALESCE(Phone.PhoneNumber +',','')+ COALESCE(Students.StreetAdress +',','')+ COALESCE(CAST(Students.ZipCode AS varchar(10)),'')AS'Adress',       COALESCE(CAST(Students.Birthdate AS varchar(11))+',','')+ COALESCE(Students.StudentType,'')AS'信息'       来自学生全部加入电话ON Students.StudentID = Phone.StudentID

提前致谢

1 个答案:

答案 0 :(得分:3)

这是一个字符串连接问题。查询在SQL Server中看起来像这样:

create view v_userphone
    select u.username, u.address,
           stuff((select ','+phonenumber
                  from userphone up
                  where up.userid = u.userid
                  for xml path ('')
                 ), 1, 1, ''
                ) as phonenumbers
    from users u;