将冗余数据合并到一个包含多个表的列中

时间:2017-06-22 02:53:48

标签: sql sql-server tsql

正如你所看到的,我在下面加入了4个表,我已经搜索了stuff函数,但它似乎只支持一个表。

DECLARE @portal varchar(100) = 'A4E7890F-A188-4663-89EB-176D94DF6774'
select 
     list.[name]     as [Company]
    ,list.[address]  as [Address]
    ,b.[name]        as [Business]
    ,comm.[value]    as [Telephone Number]
    ,pp.title + ' ' + pp.first_name + ' ' + pp.last_name as [Contact Person]

from [panpages].[listings] as list
    left join panpages.extra_communications as comm
        on comm.listing_uuid = list.uuid and comm.type = 'Tel'
    left join panpages.listing_people as lp
        on lp.listing_uuid = list.uuid
    left join panpages.people as pp
        on pp.id = lp.person_id
    left join panpages.listing_categories as r
        on r.listing_uuid = list.uuid
    left join panpages.categories as b
        on b.uuid = r.category_uuid
where
    list.[portal_uuid]=@portal and
    list.[is_active]=1 

这是我的sql代码,数据如下所示。

我目前的结果如下:

Company | Address | Business            | Telephone Number | Contact Person

A&B     | Perak   | Khmer Restaurants   | 012541           | Mr. Yu Lee
A&B     | Perak   | F&B                 | 012541           | Mr. Yu Lee
King Co.| Ipoh    | Paper Distributors  | 021453           | Mrs. Cheng
King Co.| Ipoh    | Paper Distributors  | Null             | Mrs. Cheng
DinoX   | Sunway  | Guesthouses         | 0124587          | Mr. Hong
Dinox   | Sunway  | Guesthouses         | 0124587          | Mr. Q

我的预期结果应该是这样的:

Company |Address| Business              | Telephone Number | Contact Person

A&B     | Perak | Khmer Restaurants, F&B| 012541           | Mr. Yu Lee
King Co.| Ipoh  | Paper Distributors    | 021453, Null     | Mrs. Cheng
DinoX   | Sunway| Guesthouses           | 0124587          | Mr. Hong, Mr Q

有人能帮助我吗?因为这个狗屎,我被困在4个小时左右。提前谢谢。

0 个答案:

没有答案