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> game</td> </tr> <tr> <td>player a</td> <td> easy</td> <td> game 1</td> </tr> <tr> <td>player a</td> <td> easy</td> <td> game 1</td> </tr> <tr> <td>player a</td> <td> easy</td> <td> game 2</td> </tr> <tr> <td>player b</td> <td> easy</td> <td> game 1</td> </tr> <tr> <td>player b</td> <td> medium</td> <td> game 1</td> </tr> <tr> <td>player c</td> <td> easy</td> <td> game 1</td> </tr> <tr> <td>player c</td> <td> easy</td> <td> game 2</td> </tr> <tr> <td>player c</td> <td> medium</td> <td> game 2</td> </tr> </tbody> </table> <p></p> <p>result after pivot counts.</p> <table> <tbody> <tr> <td>game</td> <td> mode</td> <td>player a</td> <td> player b</td> <td> player c</td> </tr> <tr> <td>game 1</td> <td> easy</td> <td> 2</td> <td> 1</td> <td> 1</td> </tr> <tr> <td>game 1</td> <td> medium</td> <td> 0</td> <td> 1</td> <td> 0</td> </tr> <tr> <td>game 2</td> <td> easy</td> <td> 1</td> <td> 0</td> <td> 1</td> </tr> <tr> <td>game 2</td> <td> medium</td> <td> 0</td> <td> 0</td> <td> 1</td> </tr> </tbody> </table>
you can using dynamic crosstab:
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
Post a Comment