I'm using a dynamic pivot example. This SQL code has the purpose of perform transposing data from rows to columns, using a temporary table in SQL Server.
The data is initially presented this way:
/* cLinID cLinDescr cColID cColDescr vValor ------ ------------ ------- ------------ ------------- 1 Client 01 10 Product A 110.00000000 1 Client 01 20 Product B 120.00000000 1 Client 01 30 Product C 130.00000000 2 Client 02 40 Product A 210.00000000 2 Client 02 50 Product B 220.00000000 2 Client 02 60 Product C 230.00000000 */
At the end of the process, after transform the column cColDescr
into a row, the result is shown:
/* cLinId cLinDescr Product A Product B Product C ------ --------- ------------ ------------ ------------ 1 Client 01 110.00000000 120.00000000 130.00000000 2 Client 02 210.00000000 220.00000000 230.00000000 */
Drop the temp table:
if object_id('tempdb..#pvt_temp') is not null drop table #pvt_temp
Create temp table:
create table #pvt_temp
(
cLinID int,
cLinDescr nvarchar(MAX),
cColID int,
cColDescr nvarchar(MAX),
vValor DECIMAL(20,8)
)
Data to temporary Pivot Table:
insert into #pvt_temp
values
(1, 'Client 01', 10, 'Product A', 110.0),
(1, 'Client 01', 20, 'Product B', 120.0),
(1, 'Client 01', 30, 'Product C', 130.0),
(2, 'Client 02', 40, 'Product A', 210.0),
(2, 'Client 02', 50, 'Product B', 220.0),
(2, 'Client 02', 60, 'Product C', 230.0)
Dynamic Pivot Table:
DECLARE
@ColsSelect AS NVARCHAR(MAX),
@ColsFor AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SET @ColsFor =
STUFF(
(
SELECT ',' + QUOTENAME(cColDescr)
from #pvt_temp
group by cColDescr
order by cColDescr
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @ColsSelect =
STUFF(
(
SELECT ', coalesce(' + QUOTENAME(cColDescr) + ', '''') as ' + QUOTENAME(''+ cColDescr )
from #pvt_temp
group by cColDescr
order by cColDescr
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @query =
N'SELECT
cLinId,
cLinDescr, {@ColsSelect}
from
(
select cLinId, cLinDescr, cColDescr, vValor
from #pvt_temp
) x
pivot
( sum(vValor)
for cColDescr in
({@ColsFor})
) p'
SET @query = replace(@query,'{@ColsSelect}',@ColsSelect)
SET @query = replace(@query,'{@ColsFor}' ,@ColsFor)
Data initially presented:
select * from #pvt_temp
The final result:
execute(@query)