将行合并为一个具有多个左连接的行

时间:2018-06-20 08:24:05

标签: sql sql-server-2008

我有一个如下查询:

select 
    a.person_name ,
    f.speciality,
    a.email,
    a.phone, 
    a.address
    na.descrition 'nationality',
    ci.description 'city'
    from person a
    left join lookup na on a.Country_id = na.lookup_id and na.lookup_type='FND_COUNTRIES'
    left join lookup ci on a.City_id = ci.lookup_id and ci.lookup_type='IM_CITIES'
    left join speciality pe on a.id = pe.person_id 
    left join np_speciality f on pe.speciality_id = f.speciality_id
    , 
    person_dtl b

    where a.id = b.person_id

此结果

person_name        speciality          email        phone    nationality    city  
    a                   1                                           20          30
    a                   20                                          20          30
    a                   30                                          20          30

我需要以下结果:

   person_name        speciality          email        phone    nationality    city  
    a                   1,20,30                                     20          30

我能达到同样的目的

找到了相同的答案,但由于查询中存在多个左联接,因此无法解决问题

1 个答案:

答案 0 :(得分:0)

您可以使用group_concatstuff复制for xml类型的函数。如果没有样本数据,这显然是未经测试的,但应该足够接近您的需求:

select p.person_name
      ,stuff((select ', ' + f.speciality
              from np_speciality f
              where pe.speciality_id = f.speciality_id
              for xml path('')
              )
             ,1,2,'') as speciality
      ,p.email
      ,p.phone
      ,p.address
      ,na.descrition as nationality
      ,ci.description as city
from person as p
    join person_dtl as pd
        on p.id = pd.person_id
    left join lookup na
        on p.Country_id = na.lookup_id
            and na.lookup_type = 'FND_COUNTRIES'
    left join lookup ci
        on p.City_id = ci.lookup_id
            and ci.lookup_type = 'IM_CITIES'
    left join speciality pe
        on p.id = pe.person_id

stuff用另一个定义的字符串替换由开始和结束字符号定义的字符串的一部分。在这种情况下,从字符1开始,用空白字符串替换2个字符。这是必需的,因为for xml的工作方式是

for xml会在输出中产生一个xml字符串。通过不指定任何path值和一个', '分隔符,我们得到一串由逗号和空格分隔的值,并在开头加上一个逗号和空格,并由stuff删除。

我也强烈建议您在所有脚本中使用现代join语法和有意义的别名。将join条件与逗号分隔的表以及a, b, c, etc表别名混合在一起,只会使您的代码难以阅读和维护。