I have one table. This table has total eight records. I want to show these records as column by.
My table data and assume this table name is cityreocrds.
Sr.No. City Pincode
1 Delhi 110096
2 Kaithal 136027
3 Karnal 136028
4 Kurukshetra 130029
I want this data as by column
Sr.No. Delhi Kaithal Karnal Kurukshetra
1 110096 136027 130028 130029
Note: Without pivot table it's a difficult task.
- declare @columns varchar(max)=null
- declare @temporary varchar(max)=null
- SELECT @columns = COALESCE(@columns + ','+QUOTENAME(city),QUOTENAME(city))FROM CityRecords
[delhi],[Kaithal],[Karnal],[Kurukshetra]
- set @temporary='select *
- from
- (
- select c.city as orgname,case when c.pincode=null then '''' else ''yes'' end as orgcode
- from citycode as c
- ) d
- pivot
- (
- max(orgcode) for orgname in ('+@columns+')
- ) as t2'
- exec (@temporary)

Manish Kumar ChoudharyPosted Dec 3, 2014, 6:11 AM
Nice one Joginder Banger sir..