Hi all,

I need query help for below senorio, could you please help
me.

TableName = City
CITYID ContinuationID CITYNAME
1 1 SAN
1 2 DIEGO
2 1 SAN
2 2 FRANCISCO
3 1 CHICAGO
4 1 NEW
4 2 YORK
4 3 CITY

Could you please help me to write a generalized SQL that
returns results as given below in the

Query result
CITYID NAME1 NAME2 NAME3 NAME4 NAME5
1 SAN DIEGO
2 SAN FRANCISCO
3 CHICAGO
4 NEW YORK CITY

Answer Posted / sandeep modapathi

Hi all
Gopi Muluka is right... but here I'm posting one different
thing.. ie the out put will be like this

Only two columns

It uses a function for concatination

CityID CityName
1 SAN DIEGO
2 SAN FRANCISCO
3 CHICAGO
4 NEW YORK CITY


CREATE FUNCTION DBO.GROUP_CONCAT(@CITYID VARCHAR(100))
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @STRING VARCHAR(8000)
SET @STRING=''
SELECT @STRING=@STRING+' ' +CITYNAME FROM CITY
WHERE CITYID=@CITYID ORDER BY CONTINUATIONID
RETURN LTRIM(@STRING)
END

select distinct CITYID,dbo.GROUP_CONCAT(CITYID)as CityName
from city

Is This Answer Correct ?    1 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How to modify an existing stored procedure in ms sql server?

527


Is it safe to delete log files?

519


What is normalization and what are the advantages of it?

516


Do you know the cursor types?

616


How to drop existing views from a database in ms sql server?

528






Explain the steps to create and execute a user-defined function in the sql server?

526


What options are there to delete rows on the publisher and not on the subscriber? : sql server replication

677


What is system stored procedures?

580


if you encounter this kind of an error message, what you need to look into to solve this problem? : Sql server database administration

525


What is scrollable cursor?

539


What are actions, how many types of actions are there, explain with example? : sql server analysis services, ssas

542


What is tabulation?

553


List out what other servers you can use with ssrs?

90


Is sql server is free?

538


What are the 10 characteristics of data quality?

527