2015-03-31 36 views
0

我試圖格式化這樣的數據,用於我需要編寫的報告: (每列的行數不同) 每個城市必須顯示郊區列表,並且然後列出他們擁有的車輛列表奧斯汀。SQL - 數據透視表 - 每列中行數不均勻

City Suburbs Vehicles 
    1 Austin Bastrop Ford 
    2   Hutto  Mazda 
    3   Lakeway Mercedes 
    4   Luling 
    5   ShadyHollow 
    6   WellsBranch 
    7   BrushyCreek 
    8   Elgin 
    9   Jollyville 

    10 Dallas Belmont   BMW 
    11   Eastwood  Ford 
    12   GreenlandHills 
    13   LakeParkEstates 
    14   Lochwood  

這是源數據

declare @Test0 table(city nvarchar(10), [state] varchar(30)) 
    insert into @Test0 values ('Austin', 'Texas') 
    insert into @Test0 values ('Dallas', 'Texas') 

declare @Test1 table (city nvarchar(10), suburb nvarchar(30)) 
    insert into @Test1 values ('Austin', 'Bastrop') 
    insert into @Test1 values ('Austin', 'Hutto') 
    insert into @Test1 values ('Austin', 'Lakeway') 
    insert into @Test1 values ('Austin', 'Luling') 
    insert into @Test1 values ('Austin', 'ShadyHollow') 
    insert into @Test1 values ('Austin', 'WellsBranch') 
    insert into @Test1 values ('Austin', 'BrushyCreek') 
    insert into @Test1 values ('Austin', 'Elgin') 
    insert into @Test1 values ('Austin', 'Jollyville') 
    insert into @Test1 values ('Dallas', 'Belmont') 
    insert into @Test1 values ('Dallas', 'Eastwood') 
    insert into @Test1 values ('Dallas', 'GreenlandHills') 
    insert into @Test1 values ('Dallas', 'LakeParkEstates') 
    insert into @Test1 values ('Dallas', 'Lochwood') 

    declare @Test2 table(city nvarchar(10), vehicle nvarchar(30)) 
    insert into @Test2 values ('Austin', 'Ford') 
    insert into @Test2 values ('Austin', 'Mazda') 
    insert into @Test2 values ('Austin', 'Mercedes-Benz') 
    insert into @Test2 values ('Dallas', 'BMW') 
    insert into @Test2 values ('Dallas', 'Ford') 



select * from @Test0 t0 join @Test1 t1 on t0.city = t1.city 
join @Test2 t2 on t0.city = t2.city 

從哪裏開始嗎?樞軸的答案是什麼?我甚至還在旋轉? 謝謝

回答

2
select City, 
(
select suburb + ' ' from @test1 where city=a.city for xml path(''), 
type).value('.[1]', 'varchar(max)' 
), 
(
select vehicle+ ' ' from @test2 where city=a.city for xml path(''), 
type).value('.[1]', 'varchar(max)' 
) 
from @test0 a 
+0

你好,這幾乎是工作的感謝,是有可能創造新的行,因爲它目前造成2行:市\t(沒有列名)\t(沒有列名) 奧斯汀\t BastropHuttoLakewayLulingShadyHollowWellsBranchBrushyCreekElginJollyville \t福特馬自達梅賽德斯 - 奔馳 Dallas \t BelmontEastwoodGreenlandHillsLakeParkEstatesLochwood \t寶馬福特 – 2015-03-31 15:58:55

+0

不確定你的意思是通過創建新行,你能指定它嗎? – 2015-03-31 16:56:09

+0

好吧,我已經將行號添加到原始問題了,謝謝 – 2015-03-31 18:28:09