Search
 
SCRIPT & CODE EXAMPLE
 

SQL

dynamic pivot

create table temp
(
    date datetime,
    category varchar(3),
    amount money
)

insert into temp values ('1/1/2012', 'ABC', 1000.00)
insert into temp values ('2/1/2012', 'DEF', 500.00)
insert into temp values ('2/1/2012', 'GHI', 800.00)
insert into temp values ('2/10/2012', 'DEF', 700.00)
insert into temp values ('3/1/2012', 'ABC', 1100.00)


DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.category) 
            FROM temp c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT date, ' + @cols + ' from 
            (
                select date
                    , amount
                    , category
                from temp
           ) x
            pivot 
            (
                 max(amount)
                for category in (' + @cols + ')
            ) p '


execute(@query)

drop table temp
Comment

PREVIOUS NEXT
Code Example
Sql :: snowflake last query id 
Sql :: greater than and less than in mysql query 
Sql :: SQL RIGHT JOIN With AS Alias 
Sql :: oracle generate sequence of numbers 
Sql :: oracle procedure chain step 
Sql :: SQL TABLE : SUBSCRIPTION, PRODUCT, SPECIFICATION 
Sql :: mysql error 1064 you have an error in your sql syntax 
Sql :: SQL MAX() and MIN() in Nested SELECT 
Sql :: select count(*) from table 
Sql :: for row in sql database python loop 
Sql :: PostgresDownload 
Sql :: select from another database 
Sql :: change authentication plugin from auth_sock to mysql_native_password for a specific user 
Sql :: pl sql package body 
Sql :: mysql select where field is a value 
Sql :: in operator sql 
Sql :: unable to open database database.db file is encrypted or is not a database 
Sql :: many to many getting data mysql 
Sql :: mysql a from on this page has 
Sql :: extract domain name from email id mariadb 
Sql :: How to take sum of column with same id in "JPQL?" 
Sql :: T-SQL MERGE with condition what is not matched? 
Sql :: sqlite mode default 
Sql :: sql syntax chekcer 
Sql :: ring SQLite sqlite_close 
Sql :: get last query in codeigniter 4 
Sql :: umgebungsvariable setzen für mysql 8 
Sql :: oracle sql , set operators 
Sql :: acutal month year 
Sql :: declare row variable sql server 
ADD CONTENT
Topic
Content
Source link
Name
9+1 =