0

I have this Type of Query,

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

which produce following result,

Gujarat  India
Delhi  India
HR    India
MP    India
NY    USA
LA    USA
Chicago  USA
WDC  USA
London  Uk

I want this result in single row with its relation like,

India -   Gujarat  Delhi   HR   MP
USA -   NY  LA  Chicago Uk -    London

Have Any Idea For Building this Query
Suggest Me, Thanks,

Anonymous
  • 3,679
  • 6
  • 29
  • 40
Ajay
  • 444
  • 2
  • 9

3 Answers3

2

This question is essentially a duplicate of Concatenate many rows into a single text string?.

Here is one method that works in 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;

You can see several methods for pulling off this kind of technique here: https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/

You'll need to be careful if your concatenated list of cities is going to be longer than 8000 characters, though you might be able to get away with doing something like varchar(max) if that's a concern (aside from the fact that it probably wouldn't be a very good way to look at the data).

Community
  • 1
  • 1
Bert
  • 80,741
  • 17
  • 199
  • 164
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 
Gunarathinam
  • 436
  • 1
  • 5
  • 14
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
Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281