2011-10-22 47 views
0

我有這種類型的查詢,顯示結果數據在單行中,無論是否爲。在SQL Server列的

select StateName ,countryName 
from country_master left join state_master on country_master.countryID = state_master.countryID 

其產生以下結果,

古吉拉特邦 印度
新德里 印度
HR      印度
MP      印度
NY      美國
LA      美國
芝加哥 美國
WDC  美國
倫敦 屋

我想這個結果在單行的關係一樣,

印度 -  古吉拉特邦  Delhi   HR   MP
美國 -   NY   LA  芝加哥屋 -    倫敦

有什麼想法,爲建設這個查詢
建議我, 謝謝,

+7

你應該回去,並接受正確的答案,你的過去的問題。在信用到期時給予信貸是有禮貌的,對未來類似問題的其他人有用,因爲這有助於他們迅速找到正確的答案。 –

回答

2

這個問題本質上是Concatenate many rows into a single text string?重複。

這裏有一個方法,在SQL Server 2008中的工作原理:

WITH Ranked (countryID, rnk, stateName) 
     AS (SELECT countryID, 
        ROW_NUMBER() OVER(PARTITION BY countryID ORDER BY countryID), 
        CAST(stateName AS VARCHAR(8000)) 
       FROM state_master), 
AnchorRanked (countryID, rnk, stateName) 
     AS (SELECT countryID, rnk, stateName 
       FROM Ranked 
       WHERE rnk = 1), 
RecurRanked (countryID, rnk, stateName) 
     AS (SELECT countryID, rnk, stateName 
       FROM AnchorRanked 
       UNION ALL 
       SELECT Ranked.countryID, Ranked.rnk, 
        RecurRanked.stateName + ', ' + Ranked.stateName 
       FROM Ranked 
       INNER JOIN RecurRanked 
        ON Ranked.countryID = RecurRanked.countryID 
       AND Ranked.rnk = RecurRanked.rnk + 1) 
SELECT countryName, MAX(stateName) 
    FROM RecurRanked 
    INNER JOIN country_master on RecurRanked.countryID = country_master.countryID 
GROUP BY countryName; 

你可以看到這裏脫下這種技術的幾種方法:https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/

你需要的,如果要小心你的連接的城市列表將會超過8000個字符,儘管如果這是一個問題,你可能能夠避免使用類似varchar(max)的東西(除了它可能不是一個很好的方法看數據)。

0
Select t.countryName , isnull(Stuff((SELECT ', ' + StateName 
      FROM state_master where countryID = t.countryID 
      ORDER BY StateName 
      For XML PATH ('')),1,1,''),'') as c 
from country_master t 
+0

保持簡單... – Gunarathinam

0
select c.countryName, 
     stuff((select ' '+s.StateName 
       from state_master as s 
       where s.countryID = c.countryID 
       for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '') 
from country_master as c 
相關問題