私は何をしようとしている(列の名前を動的に渡されたが、私はそれをハードコーディングされたので、それは単純に思われますこの質問)に:ダイナミックPIVOTテーブルのSQL Server 2012の
私は合計1つのフィールドピボットテーブルを使用してデータベースを照会し、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)
通常、ピボットテーブルが(私が到達しようとしている何よりも簡単です)、このようになります。列として、私はthis tutorialに続き、すべてがうまくいった。私は(それが働いている)、これまで持って何
:
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)
- :私は、私が目指すものを行うために、これまでに試した何
エラー(無効な列名)です。 @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"を合計しようとしています。私は '完全外部結合 'で試した別のクエリを投稿します。このクエリは、合計しようとしているフィールドを一覧表示します。 – StillBuggin
@KyleHale私が試したことのあるアイテム1にクエリを追加しました – StillBuggin