Convert columns to rows and a column name in SQL Server -
i want convert columns rows in sql server:
id value jan1 jan2 ---------------------- 1 2 25 35 2 5 45 45 result should be
id value month 1 2 ---------------------- 1 2 jan 25 35 2 5 jan 45 45 how can result? please help
what asking seems little strange. if extend example include columns feb1 , feb2, see 2 options transposing columns this:
+----+-------+------+------+------+------+ | id | value | jan1 | jan2 | feb1 | feb2 | +----+-------+------+------+------+------+ | 1 | 2 | 25 | 35 | 15 | 28 | | 2 | 5 | 45 | 45 | 60 | 60 | +----+-------+------+------+------+------+ transpose month part:
select id, value, monthname, monthvalue1, monthvalue2 t cross apply (values ('jan',jan1,jan2),('feb',feb1,feb2) ) v (monthname,monthvalue1,monthvalue2) returns:
+----+-------+-----------+-------------+-------------+ | id | value | monthname | monthvalue1 | monthvalue2 | +----+-------+-----------+-------------+-------------+ | 1 | 2 | jan | 25 | 35 | | 1 | 2 | feb | 15 | 28 | | 2 | 5 | jan | 45 | 45 | | 2 | 5 | feb | 60 | 60 | +----+-------+-----------+-------------+-------------+ or transpose month columns so:
select id, value, monthname, monthvalue t cross apply (values ('jan1',jan1),('jan2',jan2),('feb1',feb1),('feb2',feb2) ) v (monthname,monthvalue) returns:
+----+-------+-----------+------------+ | id | value | monthname | monthvalue | +----+-------+-----------+------------+ | 1 | 2 | jan1 | 25 | | 1 | 2 | jan2 | 35 | | 1 | 2 | feb1 | 15 | | 1 | 2 | feb2 | 28 | | 2 | 5 | jan1 | 45 | | 2 | 5 | jan2 | 45 | | 2 | 5 | feb1 | 60 | | 2 | 5 | feb2 | 60 | +----+-------+-----------+------------+ rextester demo: http://rextester.com/kzv45690
Comments
Post a Comment