SQL Server 2008 R2: Pivot table

Meem

I have the following table:

CREATE TABLE pvt
(
cola varchar(10),
colb varchar(10)
)

insert into pvt values('','2');
insert into pvt values('1','3');
insert into pvt values('9','4');
insert into pvt values('8','5');

Pivot table Query:

DECLARE @StuffColumn varchar(max)
DECLARE @sql varchar(max)

SELECT @StuffColumn = STUFF((SELECT ','+QUOTENAME(cola) 
                        FROM pvt
          FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')
PRINT(@StuffColumn)        

SET @SQL = ' select colb,'+ @StuffColumn +'
         from
         (
            select cola,colb
            from pvt
         )x
         pivot
         (
             count(cola)
             for cola in( '+@StuffColumn +')
         )p'
PRINT(@SQL)
EXEC(@SQL)           

Error:

Msg 1038, Level 15, State 4, Line 1
An object or column name is missing or empty. For SELECT INTO statements, 
verify each column has a name. For other statements, look for empty alias 
names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.

Expected Result:

colb      1  9   8       
-------------------
 2    1   0  0   0
 3    0   1  0   0
 4    0   0  1   0
 5    0   0  0   1
Milen

How about this:

DECLARE @StuffColumn varchar(max)
DECLARE @sql varchar(max)

SELECT @StuffColumn = STUFF((SELECT ','+QUOTENAME(case when cola = '' then 'empty' else cola end) 
                        FROM pvt
          FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')
PRINT(@StuffColumn)        

SET @SQL = ' select colb,'+ @StuffColumn +'
         from
         (
            select case when cola = '''' then ''empty'' else cola end as cola,colb
            from pvt
         )x
         pivot
         (
             count(cola)
             for cola in( '+@StuffColumn +')
         )p'
PRINT(@SQL)
EXEC(@SQL)  

You need to give name to your pivot columns.

Solution for more than one empty column + dynamic pivot:

DECLARE @StuffColumn varchar(max)
DECLARE @sql varchar(max)

SELECT @StuffColumn = STUFF((SELECT ','+QUOTENAME(case when cola = '' then Cast(ROW_NUMBER() over (order by colb) as varchar (6))  + 'empty' else cola end) 
                        FROM pvt
          FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')
PRINT(@StuffColumn)        

SET @SQL = ' select colb,'+ @StuffColumn +'
         from
         (
            select   case when cola = '''' then Cast(ROW_NUMBER() over (order by colb) as varchar (6)) +''empty'' else cola end cola,colb
            from pvt
         )x
         pivot
         (
             count(cola)
             for cola in( '+@StuffColumn +')
         )p'
PRINT(@SQL)
EXEC(@SQL)  

Demo here

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Pivot table query using SQL Server 2008 R2

SQL Server 2008 R2: Pivot table with count

SQL Server 2008 R2: Dynamic Pivot table query performance

SQL Server 2008 R2 - Pivot Usage?

Pivot table in SQL Server 2008

sql server 2008 pivot table

sql server 2008 R2 management studio table recreation

SQL Server 2008 pivot table with dates

Pivot table Q - SQL Server 2008

SQL Server 2008 R2 Dynamic Pivot Query with bit types

Getting Null data while using PIVOT in sql server 2008 R2

SQL Server 2008 R2 - Dynamic Pivot/Unpivot with (moving) Dates

SQL Server 2008 - Pivot

BCP from One Table to Another table in different servers in SQL Server 2008 R2

SQL Server 2008 R2: Update table values which matched with another table

How to pull data from one table based on a temp table SQL Server 2008 R2?

SQL Server 2008 R2 : calculate columns of a table based on values of another table

How to get list of constraints of a table along with their respective column names in SQL Server 2008 R2

Exporting a table from SQL Server 2008 R2 to a file WITHOUT external tools

SQL Server 2008 R2: Get table_name from view from other database

Select datetime column from SQL Server 2008 R2 table

How much space does an empty table use in Microsoft SQL Server 2008 R2?

SQL Server 2008 R2: selecting record which are present in another table

How to create a table with a column that will automatically compute the sum of the other column using SQL Server 2008 R2?

Delete the non-duplicate row from actual Database Table in SQL Server 2008 R2

Create SQL Server 2008 Backup from 2008 R2

SQL Server 2008 PIVOT and JOIN

SQL Server 2008 result pivot

cannot access a data table located in another server from a stored procedure in one server of SQL server 2008 R2 management studio