SQL Server Pivot Data -


can me out. how i'm storing records in 1 of tables in sql server.
how can use pivot/unpivot represent data below table in expected format shown below. in advance.

<p>table - scores</p>  <table>  <tbody>  <tr>  <td>name</td>  <td>mode</td>  <td>&nbsp;game</td>  </tr>  <tr>  <td>player a</td>  <td>&nbsp;easy</td>  <td>&nbsp;game 1</td>  </tr>  <tr>  <td>player a</td>  <td>&nbsp;easy</td>  <td>&nbsp;game 1</td>  </tr>  <tr>  <td>player a</td>  <td>&nbsp;easy</td>  <td>&nbsp;game 2</td>  </tr>  <tr>  <td>player b</td>  <td>&nbsp;easy</td>  <td>&nbsp;game 1</td>  </tr>  <tr>  <td>player b</td>  <td>&nbsp;medium</td>  <td>&nbsp;game 1</td>  </tr>  <tr>  <td>player c</td>  <td>&nbsp;easy</td>  <td>&nbsp;game 1</td>  </tr>  <tr>  <td>player c</td>  <td>&nbsp;easy</td>  <td>&nbsp;game 2</td>  </tr>  <tr>  <td>player c</td>  <td>&nbsp;medium</td>  <td>&nbsp;game 2</td>  </tr>  </tbody>  </table>  <p></p>  <p>result after pivot counts.</p>  <table>  <tbody>  <tr>  <td>game</td>  <td>&nbsp;mode</td>  <td>player a</td>  <td>&nbsp;player b</td>  <td>&nbsp;player c</td>  </tr>  <tr>  <td>game 1</td>  <td>&nbsp;easy</td>  <td>&nbsp;2</td>  <td>&nbsp;1</td>  <td>&nbsp;1</td>  </tr>  <tr>  <td>game 1</td>  <td>&nbsp;medium</td>  <td>&nbsp;0</td>  <td>&nbsp;1</td>  <td>&nbsp;0</td>  </tr>  <tr>  <td>game 2</td>  <td>&nbsp;easy</td>  <td>&nbsp;1</td>  <td>&nbsp;0</td>  <td>&nbsp;1</td>  </tr>  <tr>  <td>game 2</td>  <td>&nbsp;medium</td>  <td>&nbsp;0</td>  <td>&nbsp;0</td>  <td>&nbsp;1</td>  </tr>  </tbody>  </table>

you can using dynamic crosstab:

sql fiddle

declare @sql1 varchar(2000) = '' declare @sql2 varchar(2000) = '' declare @sql3 varchar(2000) = ''  select @sql1 =  'select     game     , mode' + char(10)  select @sql2 = @sql2 + '   , sum(case when name = ''' + name + ''' 1 else 0 end) ' + quotename(name) + char(10) from(     select distinct name scores )t order name  select @sql3 =  'from scores group game, mode order game, mode'  print(@sql1 + @sql2 + @sql3) exec(@sql1 + @sql2 + @sql3) 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -