sql server - Transpose the columns to rows -
i have result set table such following picture:
returned following query:
select [id],[siteid],[variableid],[qualifierid],[value],[valuedate],[insertdate],[insertuserid] ,[deletedate],[deleteuserid],[datastatus] mytable
i transpose according other picture:
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:
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);
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):
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:
Comments
Post a Comment