Monday, 19 August 2013

SQL Pivoting or Transposing or ... column to row?

SQL Pivoting or Transposing or ... column to row?

I have a question and this looks way better in SQLfiddle:
http://www.sqlfiddle.com/#!3/dffa1/2
I have a table with multirows for each user with datestamp and test
results and i would like to transpose or pivot it into one line result as
follows where each user has listed all time and value results:
USERID PSA1_time PSA1_result PSA2_time PSA2_result PSA3_time PSA3_result ...
1 1999-.... 2 1998... 4 1999... 6
3 1992... 4 1994 6
4 2006 ... 8
Table below:
CREATE TABLE yourtable ([userid] int, [Ranking] int,[test] varchar(3),
[Date] datetime, [result] int) ;
INSERT INTO yourtable ([userid], [Ranking],[test], [Date], [result])
VALUES ('1', '1', 'PSA', 1997-05-20, 2), ('1', '2','PSA', 1998-05-07, 4),
('1', '3','PSA', 1999-06-08, 6), ('1', '4','PSA', 2001-06-08, 8), ('1',
'5','PSA', 2004-06-08, 0), ('3', '1','PSA', 1992-05-07, 4), ('3',
'2','PSA', 1994-06-08, 6), ('4', '1','PSA', 2006-06-08, 8) ;

No comments:

Post a Comment