1

I'm working in SQL 2008. My table is 3 COLUMNS x 9546 ROWS, WHERE DATA IS LIKE

Type     Age       Value
0        30        .24
0        31        .54
0        32        .34
.
.
.
0       115        .23
1       30         .45
1       31         .33
.
.
.
1       115        .32
2       30         .11
.
.
.
2       115        .22
.
.
.
110     115        .86

I want the final table to look like

Type   30     31      32     . . .    115
0      .24    .54     .34    . . .     .23
1      .45    .33      . . .  
.
.
.
110    . . . 

Basically, Type goes vertically and Age goes horizontally.

What is the simplest way to doing this?

Thank you!!

squillman
  • 13,363
  • 3
  • 41
  • 60
Jamie Hong
  • 21
  • 2
  • 3
    Possible duplicate of [Understanding PIVOT function in T-SQL](http://stackoverflow.com/questions/10428993/understanding-pivot-function-in-t-sql) – JNevill Apr 26 '16 at 18:52
  • 2
    Possible duplicate of [Convert Rows to columns using 'Pivot' in SQL Server](http://stackoverflow.com/questions/15931607/convert-rows-to-columns-using-pivot-in-sql-server) – zebediah49 Apr 26 '16 at 18:53
  • I cant manually type any of these numbers and Would like to have general query that would work for this column name and structure. But thanks tho!! (Don't think im good enough to alter one above ; ( ) – Jamie Hong Apr 26 '16 at 18:56
  • You don't need to manually type in the numbers. SQL Server's built in PIVOT functionality will do everything you need to do here. Your example is like Pivot101 too, so it should be a snap. Check out @zebediah49's link as that is also a super simple pivot. Just replace that example with your field and table names and hit the go button. – JNevill Apr 26 '16 at 18:57
  • May I ask which answer to look at? it just looks too confusing to me.. ; ( – Jamie Hong Apr 26 '16 at 18:59
  • bluefeet's answer will work. Don't worry about the dynamic part of his answer. Just take that first SQL statement and swap everything out with your fields and tables and you should get exactly what you want. PIVOTs can be hard to wrap your head around it first, but they are terribly useful (like Recursive SQL and Window Functions). Once you "get it" you can write some powerful sql. – JNevill Apr 26 '16 at 19:02
  • Thanks. Dynamic one helped me.!! – Jamie Hong Apr 26 '16 at 19:13

0 Answers0