This question already has an answer here:
this is my query
select * from dbo.tblHRIS_ChildDetails where intSID=463
output:
intCHID intsid nvrchildname nvrgender dttchildDOB Occupation
3 463 SK Female 2001-12-11 00:00:00.000 Studying
4 463 SM Male 2007-10-08 00:00:00.000 Student
i need the output like this this is query is dynamic it may return n number of rows based on the intSID
chidname1 gender DOB childoccupation1 chidname2 gender DOB childoccupation2
SK female 2001-12-11 00:00:00.000 studying SM Male 2007-10-08 00:00:00.000 Student
You have to provide distinct column names but besides that, it's simple. But as others stated, this is not commonly done and looks like if you want print some report with two columns.
For this type of data, you will need to implement both the
UNPIVOT
and then thePIVOT
functions of SQL Server. TheUNPIVOT
takes your data from the multiple columns and place it into two columns and then you apply thePIVOT
to transform the data back into columns.If you know all of the values that you want to transform, then you can hard-code it, similar to this:
See SQL Fiddle with Demo
Now, if you have an unknown number of values to transform, then you can use dynamic SQL for this:
See SQL Fiddle with Demo
The result of both queries is: