December 18, 2014 at 4:20 am
Hi Team,
I need to convert the column to rows but within group. example
Group Name Value
p a 1
p b 2
p c 3
p d 4
q a 5
q b 6
q d 7
r a 8
r b 9
r c 10
r d 11
This need to be transposed to :
Group a b c d
p1234
q56NULL7
r891011
Any help would be great !
Thanks
December 18, 2014 at 4:34 am
CREATE TABLE #Temp([Group] CHAR(1),Name CHAR(1),Value INT)
INSERT INTO #Temp([Group],Name,Value)
SELECT 'p','a',1 UNION ALL
SELECT 'p','b',2 UNION ALL
SELECT 'p','c',3 UNION ALL
SELECT 'p','d',4 UNION ALL
SELECT 'q','a',5 UNION ALL
SELECT 'q','b',6 UNION ALL
SELECT 'q','d',7 UNION ALL
SELECT 'r','a',8 UNION ALL
SELECT 'r','b',9 UNION ALL
SELECT 'r','c',10 UNION ALL
SELECT 'r','d',11
SELECT [Group],
SUM(CASE WHEN Name = 'a' THEN Value END) AS [a],
SUM(CASE WHEN Name = 'b' THEN Value END) AS ,
SUM(CASE WHEN Name = 'c' THEN Value END) AS [c],
SUM(CASE WHEN Name = 'd' THEN Value END) AS [d]
FROM #Temp
GROUP BY [Group]
____________________________________________________
Deja View - The strange feeling that somewhere, sometime you've optimised this query before
How to get the best help on a forum
http://www.sqlservercentral.com/articles/Best+Practices/61537December 23, 2014 at 10:57 pm
CREATE TABLE #Temp([Group] CHAR(1),Name CHAR(1),Value INT)
INSERT INTO #Temp([Group],Name,Value) values
('p','a',1),
('p','b',2),
('p','c',3),
('p','d',4),
('q','a',5),
('q','b',6),
('q','d',7),
('r','a',8),
('r','b',9),
('r','c',10),
('r','d',11)
SELECT [Group],a,b,c,d FROM
(
SELECT [GROUP],Name,value FROM #Temp
) AS P
Pivot
(
sum(value)
for name in([a],,[c],[d])
) as pvt
order by pvt.[Group]
January 4, 2015 at 12:01 pm
For more information on how that works and an alternative along with some performance testing, please see the following article...
http://www.sqlservercentral.com/articles/T-SQL/63681/
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply