Click here to Skip to main content
15,887,822 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My current table is

id name phone address
-- ------------------------------
2 manoj 456 wes
3 senthil 789 east

I want to show

id 2 3
---------------------------
name manoj senthil
phone 456 789
address wes es

I am trying this in pivot concept am i in correct route
Posted

Pivot is one way to transform the data. But first of all, since I don't know where you're going to use the solution I would advice to make all the formatting, layouts etc somewhere else than in an SQL statement. SQL is a language designed for data retrieval and modification. Typically it's best that the formatting is done with tools designed for that (such as reporting tools etc.)

Having that said, consider the following example

SQL
CREATE TABLE t1 (
   id int,
   name varchar(100),
   phone varchar(100),
   address varchar(100)
);

INSERT INTO t1 VALUES (2, 'manoj',  '456', 'wes');

INSERT INTO t1 VALUES (3, 'senthil', '789', 'east');


SELECT 'name' as subject, pvt.[2], pvt.[3]
FROM (SELECT id, name
	  FROM t1) p
PIVOT (
	max (name)
	FOR id IN ([2], [3])
) AS pvt
UNION ALL
SELECT 'phone' as subject, pvt.[2], pvt.[3]
FROM (SELECT id, phone
	  FROM t1) p
PIVOT (
	max (phone)
	FOR id IN ([2], [3])
) AS pvt
UNION ALL
SELECT 'address' as subject, pvt.[2], pvt.[3]
FROM (SELECT id, address
	  FROM t1) p
PIVOT (
	max (address)
	FOR id IN ([2], [3])
) AS pvt


This would result to
subject	2	3
------- ------- -------
name	manoj	senthil
phone	456	789
address	wes	east
 
Share this answer
 
Comments
Arasappan 10-Jul-15 5:17am    
I have onemore suggestion here. In future i am going to add the data in t1 mean in every time i am going add in query like[4],[5] is there any dynamic mean please refer.
Wendelius 10-Jul-15 5:20am    
Exactly, when you add new data rows into the table you need to add new columns to this query since each column represents a single data row.

This is exactly the reason why I suggest using other tools than SQL. Of course you can create the SQL statement dynamically based on the data but this introduces much complexity which can be avoided by selecting correct tool for the job.
Yup - pivot is correct.

Short answers never feel complete so here's an article on implementing them:

Simple Way To Use Pivot In SQL Query[^]
 
Share this answer
 
Comments
Arasappan 10-Jul-15 3:58am    
hmm.. Thank you .. for thousand miles of journey first step is important . thank you :-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900