【发布时间】:2016-09-03 13:36:47
【问题描述】:
我正在尝试做的事情(列名是动态传递的,但我是硬编码的,所以这个问题看起来更简单):
我正在尝试使用 PIVOT 表查询数据库以汇总一个字段并计算 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
pivot(
count(Setor)
for Setor in(' + @campos + ')
) 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
pivot(
count(Setor)
for Setor in(' + @campos + ')
) b
select * from #temp_total'
execute(@resultado)
到目前为止,我为实现我的目标所做的努力:
- 我复制了 PIVOT 部分并尝试执行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 (
(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)
- 我尝试UNPIVOT and PIVOT method,这也会产生无效列的错误。
【问题讨论】:
-
你在对哪个字段求和?此处列出的所有字段都是文本字段。
-
非常感谢您的回复。我正在尝试对“Valor_do_Emprestimo”字段求和。我将发布另一个我尝试使用
full outer join的查询。此查询列出了我要求和的字段。 -
@KyleHale 我将查询添加到我尝试过的事情的第 1 项
标签: sql sql-server tsql sql-server-2012