I'm struggling with implementing pandas crosstab function in an SQL script. I have a table which looks like this:
User | Code | Used
user1 | <null> | 1
user2 | abca | 4
user2 | <null> | 2
---
userN | baaa | 3
My goal is a table like this:
| <null> | abca | baaa
user1 | 1 | 0 | 0
user2 | 2 | 4 | 0
---
userN | 0 | 0 | 1
So far I used this code, taken from here, but it returns an empty table:
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
SELECT @ColumnName= User FROM temp2
SET @DynamicPivotQuery =
N'SELECT * from (
SELECT User, Code, Used
FROM temp2) as src
PIVOT
(
sum(Used) as sum FOR Code IN (' + @ColumnName + ')
) as piv'
EXEC sp_executesql @DynamicPivotQuery
SELECT @DynamicPivotQuery
There are literally hundreds of codes used, so apparently I need to use a dynamic pivot table, so I don't have to list all the codes. Zero values need to remain. I tried pretty much everything I could find on the Internet and StackOverflow, including this, this and many more. I'd appreciate any leads.