我想要做的(列的名稱是動態過去了,但我硬編碼,因此它似乎更簡單在這個問題上):動態數據透視表SQL Server 2012中使用COUNT()和SUM()和Total列
我想查詢使用數據透視表數據庫來和一個字段和計數在SQL Server 2012中的表的行,但是,除此之外,我想檢索彙總到的COUNT()和SUM()函數。
通常情況下,數據透視表是這樣的(這是比什麼,我試圖達到簡單):
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
\t \t pivot(
\t \t count(Setor)
\t \t \t for Setor in(' + @campos + ')
\t \t ) a'
execute(@resultado)
我有什麼事這麼遠(這是工作):
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
\t \t pivot(
\t \t count(Setor)
\t \t \t for Setor in(' + @campos + ')
\t \t ) b
select * from #temp_total'
execute(@resultado)
我試過到目前爲止做什麼,我的目標是:
- 我複製樞紐部,並試圖做一個FULL OUTER JOIN,但問題是,它是重複的列到最後的結果是什麼產生一個錯誤(無效的列名稱)。當我打印@resultado時,它就是列正在複製。
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 (
\t \t (select Setor, ''br-'' + lower(UF_FILIAL) as [hc-key] from dbo.TbFinanciamentos
\t \t \t \t pivot(
\t \t \t \t \t count(Setor)
\t \t \t \t \t for Setor in(' + @campos + ')
\t \t \t \t ) as b
\t \t \t ) as sth
\t \t \t full outer join
\t \t \t (
\t \t select cast(Valor_do_Emprestimo as float) as Valor_do_Emprestimo, Setor, ''br-'' + lower(UF_FILIAL) as [hc-key] from dbo.TbFinanciamentos
\t \t \t \t pivot(
\t \t \t \t \t count(Setor)
\t \t \t \t \t for Setor in(' + @campos + ')
\t \t \t \t ) as b
\t \t \t ) as sth_else
\t \t \t on sth.[hc-key] = sth_else.[hc-key]
\t \t )
select * from #temp_total'
execute(@resultado)
- 我試圖UNPIVOT and PIVOT method產生無效列的誤差爲好。
究竟是什麼字段?這裏列出的所有字段都是文本字段。 –
非常感謝你的回覆。我正在嘗試總結「Valor_do_Emprestimo」字段。我會發布另一個我用'full outer join'試過的查詢。此查詢列出了我試圖總結的字段。 – StillBuggin
@KyleHale我將查詢添加到我嘗試的東西的項目1中 – StillBuggin