Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Try this example:</p> <pre><code>if object_id('tempdb..#student') is not null drop table #student create table #student ( sid int ,sname varchar(10) ,lastname varchar(10) ,age int ) insert #student select 1,'Joe','Block',20 union all select 2,'Adam','Brad',30 union all select 3,'Kevin','Campbell',33 union all select 4,'Mike','Gust',40 SELECT * FROM #student if object_id('tempdb..#course') is not null drop table #course create table #course ( cid int ,sid int ,coursename varchar(15) ,duration int ,courselanguage varchar(10), pos varchar(15) ) insert #course select 1,1,'Maths',2,'English',2 union all select 2,1,'Science4',1,'Spanish4',1 union all select 2,1,'Science',1,'Spanish',3 union all select 3,1,'Geography',1,'Dutch',4 union all select 4,2,'Maths',2,'Dutch',2 union all select 5,2,'Science',2,'English',4 union all select 5,4,'test',545,'testlang',2 SELECT * FROM #course declare @maxcourses int select @maxcourses=(select max(numcourses) from (select numcourses=count(*) from #course group by sid) q) declare @pivotlist varchar(max) ,@pivotselectlist varchar(max) select @pivotlist= coalesce(@pivotlist+',','') +'Sub'+ix+',' +'Dur'+ix+',' +'Lang'+ix ,@pivotselectlist= coalesce(@pivotselectlist+',','') +'Sub'+ix+'=coalesce(Sub'+ix+','''')'+',' +'Dur'+ix+'=coalesce(cast(Dur'+ix+' as int),0)'+',' +'Lang'+ix+'=coalesce(Lang'+ix+','''')' from (select ix=convert(varchar(3),Number) from master..spt_values where Type='P' and Number between 1 and @maxcourses) q declare @sql nvarchar(max) set @sql=' ;with Rnums as ( select sid ,coursename ,duration ,courselanguage ,ix=pos from #course ) ,PivotInput as ( select sid ,AttribName=case ColNo when 1 then ''Sub''+ix when 2 then ''Dur''+ix when 3 then ''Lang''+ix end ,AttribVal=case ColNo when 1 then coursename when 2 then cast(duration as varchar(10)) when 3 then courselanguage end from Rnums cross join (select 1 union all select 2 union all select 3) Cols(ColNo) ) ,PivotCourses as ( select sid,'+@pivotlist+' from PivotInput pivot (max(AttribVal) for AttribName in ('+@pivotlist+') ) PivotOutput ) select s.sid ,sname ,lastname ,age ,'+@pivotselectlist+' from #student s join PivotCourses c on s.sid=c.sid' --print @sql exec sp_executesql @sql </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload