-2

我有以下兩個表顯示多個值一行

TableA   Table B 

id    bid bname  btitle 
----    ------------------------------ 
1    1 john  titlejohn 
2    1 william titlewilliam 
3    1 george titlegeorge 
       2 bill  titlebill 
       3 kyle  titlekyle 
       3 seb  titleseb 

我需要在SQL Server查詢,顯示下面的輸出:

id name      title 
1 john,william,george  titlejohn,titlewilliam,titlegeorgw 
2 bill      titlebill 
3 kyle,seb     titlekyle,titleseb 

請幫助。

回答

1

這裏有一個解決方案。它只處理bname,但您可以擴展它以處理btitle。給定鍵的列值並不是SQL中的自然事物,因此您需要一個技巧來循環訪問使用相同鍵提取每行的表。訣竅是創建一個內存表與標識列(n說),每個插入自動增量。你可以循環,然後選擇n = 1,然後n = 2等來構建字符串。

create function tbl_join_name(@id int) 
returns varchar(max) 
as 
begin 
    declare @tbl table (n int identity(1,1), name varchar(max), title varchar(max)) 
    insert @tbl(name, title) 
    select bname, btitle from TableB where bid = @id 

    declare @n int = 1, @name varchar(max) = '', @count int = (select count(*) from @tbl) 
    while @n <= @count begin 
     set @name = @name + (case @name when '' then '' else ',' end) + (select name from @tbl where n = @n) 
     set @n = @n + 1 
    end 
    return @name 
end 
go 

select id, tbl_join_name(id) as bname --, tbl_join_title(id) as btitle 
from TableA 

雖然這不是很有效率。使用Sql Server 2008 R2進行測試。

2
select id, name = stuff(n.name, 1, 1, ''), title = stuff(t.title, 1, 1, '') 
from TableA a 
    outer apply 
    (
     select ',' + bname 
     from TableB x 
     where x.bid = a.id 
     for xml path('') 
    ) n (name) 
    outer apply 
    (
     select ',' + btitle 
     from TableB x 
     where x.bid = a.id 
     for xml path('') 
    ) t (title) 
0

的另一種方法:

SELECT A.id, 
     STUFF((SELECT ','+bname 
     FROM TableB B 
     WHERE B.bid = A.id 
     FOR XML PATH('')),1,1,'') as name, 
     STUFF((SELECT ','+btitle 
     FROM TableB B 
     WHERE B.bid = A.id 
     FOR XML PATH('')),1,1,'') as title 
FROM TableA A 

輸出:

id name    title 
1 john,william,george titlejohn,titlewilliam,titlegeorge 
2 bill    titlebill 
3 kyle,seb   titlekyle,titleseb