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 / gopi muluka
Using PIVOT operator we can achieve this in SQL 2005
CREATE TABLE CITY (CITYID INT, ContinuationID INT, CITYNAME
VARCHAR(50))
GO
INSERT CITY
SELECT 1 ,1, 'SAN'
UNION ALL
SELECT 1, 2, 'DIEGO'
UNION ALL
SELECT 2, 1, 'SAN'
UNION ALL
SELECT 2, 2, 'FRANCISCO'
UNION ALL
SELECT 3, 1, 'CHICAGO'
UNION ALL
SELECT 4, 1, 'NEW'
UNION ALL
SELECT 4, 2, 'YORK'
UNION ALL
SELECT 4, 3, 'CITY'
GO
SELECT CITYID, [1] AS NAME1,[2] AS NAME2,[3] AS NAME3, [4]
AS NAME4
FROM
(
SELECT CITYID,ContinuationID, CITYNAME
FROM CITY
) P
PIVOT
(
MAX(CITYNAME)
FOR ContinuationID IN
([1],[2],[3],[4])
) AS PVT
ORDER BY CITYID
GO
DROP TABLE CITY
| Is This Answer Correct ? | 5 Yes | 0 No |
Post New Answer View All Answers
How many tables can be joined in SQL Server?
What is a view and what are its advantages?
What are the restraints imposed on the table design by a merge replication?
How to create indexed view?
How to use wildcard characters in like operations in ms sql server?
How to provide column names in insert statements in ms sql server?
What is sql server transaction log file?
What is replace and stuff function in sql server?
What is the difference between executequery () and executeupdate ()?
What are the underflow and overflow behaviors on float literals?
what's sql server? : Sql server database administration
explain different types of joins? : Sql server database administration
What is stored in the mssqlsystemresource database? : sql server database administration
Explain filtered indexes benefits?
What is wrong with sql server client libarary dll, ntwdblib.dll?