2011-10-22 50 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