Search
 
SCRIPT & CODE EXAMPLE
 

SQL

SQL Server dynamic pivot unknown number of columns

-   DECLARE @v_query  VARCHAR(8000) -- main query
    DECLARE @v_columns VARCHAR(8000) -- columns

    SET @v_columns =''

    -- Get string columns
    SELECT @v_columns += '[' + CONVERT(VARCHAR, Item) +'],' FROM (SELECT DISTINCT Item FROM #temp2) AS temp

    -- Delete the last comma
    SET @v_columns = LEFT(@v_columns,LEN(@v_columns)-1)


    -- Main query

    SET @v_query = 'SELECT Name, ' + @v_columns +' FROM
                    (
                        SELECT Name, Item FROM #temp2
                    ) T             
                    PIVOT
                    (
                        Count(Item)
                        FOR Item IN ('+ @v_columns +')
                    ) PVT'
    EXEC (@v_query)
Comment

PREVIOUS NEXT
Code Example
Sql :: mysql workbench reset performance reports 
Sql :: SQL Comments With Statements 
Sql :: how to find symmetric pairs in sql 
Sql :: online compiler for sql plus 
Sql :: how to count codition 
Sql :: decode plsql 
Sql :: sql int vs integer 
Sql :: like sql for second letter of the family name 
Sql :: Serilog Table Configurations for MSSQLSERVER SINK 
Sql :: 5000/208 
Sql :: hive hbase create external table 
Sql :: storing RGBA in mysql db 
Sql :: oracle execute immediate quotes 
Sql :: mysql update column with value from another table 
Sql :: displaying different entities from different tables at once 
Sql :: user defined variables in sql 
Sql :: learnxinyminutes sql 
Sql :: qt qsql check if table exist 
Sql :: sql fetch next 10 rows pdo 
Sql :: oracle run_duration to number 
Sql :: Postpresql relation not found 
Sql :: sql examples from your work 
Sql :: ERROR: column "hourly_visitors.hour" must appear in the GROUP BY clause or be used in an aggregate function 
Sql :: sql insert multiple rows from another table 
Sql :: select from another database 
Sql :: turnicate in mysql 
Sql :: watch mysql command line 
Sql :: How to pass list as parameter in SQL query 
Sql :: oracle update multiple columns 
Sql :: convert sqlalchemy.util._collections to list of string 
ADD CONTENT
Topic
Content
Source link
Name
9+4 =