What I'm trying to do (the name of the column is passed dynamically, but I hard-coded it, so it seems simpler in this question):
I am trying to query a database using PIVOT tables to sum one field and count the rows of a SQL Server 2012 table, but, in addition, I am trying to retrieve totals to the COUNT() and SUM() functions.
Normally, a pivot table would look like this (which is simpler than what I am trying to reach):
declare @campos nvarchar (max)
select @campos = coalesce(@campos + ',[' + Setor + ']', '[' + Setor + ']')
from dbo.TbFinanciamentos
group by Setor
order by Setor
declare @resultado nvarchar(max)
set @resultado =
'select * from(select Setor, ''br-'' + lower(UF_FILIAL) as [hc-key] from dbo.TbFinanciamentos) a
pivot(
count(Setor)
for Setor in(' + @campos + ')
) a'
execute(@resultado)

What I have so far (that's working):
declare @campos nvarchar (max)
select @campos = coalesce(@campos + ',[' + Setor + ']', '[' + Setor + ']')
from dbo.TbFinanciamentos
group by Setor
order by Setor
declare @total nvarchar(max)
select @total = coalesce(@total + 'isnull([' + Setor + '], 0) + ', 'isnull([' + Setor + '], 0) + ')
from dbo.TbFinanciamentos group by Setor order by Setor
set @total = left(@total, len(@total) - 1)
declare @resultado nvarchar(max)
set @resultado =
'select *, '+ @total +' as [value] into #temp_total
from (select Setor, ''br-'' + lower(UF_FILIAL) as [hc-key] from dbo.TbFinanciamentos) a
pivot(
count(Setor)
for Setor in(' + @campos + ')
) b
select * from #temp_total'
execute(@resultado)

What I tried so far to do what I aim to:
- I duplicated the PIVOT part and tried to do a FULL OUTER JOIN, but the problem is that it is repeating the columns to the final result what generates an error (Invalid column name). When I print @resultado, there it is, columns are duplicating.
declare @campos nvarchar (max)
select @campos = coalesce(@campos + ',[' + Setor + ']', '[' + Setor + ']')
from dbo.TbFinanciamentos
group by Setor
order by Setor
declare @total nvarchar(max)
select @total = coalesce(@total + 'isnull([' + Setor + '], 0) + ', 'isnull([' + Setor + '], 0) + ')
from dbo.TbFinanciamentos group by Setor order by Setor
set @total = left(@total, len(@total) - 1)
declare @resultado nvarchar(max)
set @resultado =
'select *, '+ @total +' as [value] into #temp_total
from (
(select Setor, ''br-'' + lower(UF_FILIAL) as [hc-key] from dbo.TbFinanciamentos
pivot(
count(Setor)
for Setor in(' + @campos + ')
) as b
) as sth
full outer join
(
select cast(Valor_do_Emprestimo as float) as Valor_do_Emprestimo, Setor, ''br-'' + lower(UF_FILIAL) as [hc-key] from dbo.TbFinanciamentos
pivot(
count(Setor)
for Setor in(' + @campos + ')
) as b
) as sth_else
on sth.[hc-key] = sth_else.[hc-key]
)
select * from #temp_total'
execute(@resultado)
- I tried to UNPIVOT and PIVOT method which generates an error of invalid columns as well.