sql server - Transpose the columns to rows -


i have result set table such following picture:

enter image description here

returned following query:

select [id],[siteid],[variableid],[qualifierid],[value],[valuedate],[insertdate],[insertuserid] ,[deletedate],[deleteuserid],[datastatus] mytable 

i transpose according other picture:

enter image description here

i have tried follow pivot samples couldn't reach result. attempt (i did not include columns):

select  [1281] q1, [1282] q2, [1283] q3, [1284] q4, [1285] q5, [1286] q6, [1287] q7, [1288] q8, [1289] q9  ( select  id, qualifierid, value, insertdate badmentries variableid=1000) p pivot (     max(value)     qualifierid in     ( [1281] , [1282], [1283], [1284], [1285], [1286], [1287], [1288], [1289] ) ) pvt 

but did not work, because result get: enter image description here

where error?! thanks, diego

remove id column sub-query not using in pivot clause , in final select statement used grouping:

select  [1281] q1, [1282] q2, [1283] q3, [1284] q4, [1285] q5, [1286] q6, [1287] q7, [1288] q8, [1289] q9  ( select  qualifierid, value, insertdate badmentries variableid=1000) p pivot (     max(value)     qualifierid in     ( [1281] , [1282], [1283], [1284], [1285], [1286], [1287], [1288], [1289] ) ) pvt 

explanation:

let's have following table:

declare @datasource table (     [recordid] tinyint    ,[team] varchar(12)    ,[matchid] tinyint    ,[score] tinyint );  insert @datasource ([recordid], [team], [matchid], [score]) values (1, 'a', 1, 50)       ,(2, 'a', 2, 10)       ,(3, 'b', 1, 20)       ,(4, 'b', 2, 40)       ,(5, 'b', 3, 70); 

enter image description here

and want make pivot [matchid] column , write following query:

select *  (     select *     @datasource ) ds pivot (     max([score]) [matchid] in ([1], [2], [3]) ) pvt; 

i getting following result (similar you):

enter image description here

the issue "caused" recordid column unique , results group it. so, fix issue need remove it:

select *  (     select [team]           ,[matchid]           ,[score]     @datasource ) ds pivot (     max([score]) [matchid] in ([1], [2], [3]) ) pvt; 

and works fine:

enter image description here


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -