带有COUNT()和SUM()以及TOTAL列的动态PIVOT表SQL Server 2012

时间:2016-05-09 02:18:45

标签: sql sql-server tsql sql-server-2012

我想做的事情(列的名称是动态传递的,但我对其进行了硬编码,因此在这个问题上似乎更简单):

我正在尝试使用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)



 enter image description here 但是,我希望将总数(总计)列为一列,而不是我跟随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
		 pivot(
		     count(Setor)
			 for Setor in(' + @campos + ')
		 ) b
         select * from #temp_total'

execute(@resultado)



 enter image description here 但是,正如我为COUNT()所做的那样,我想为SUM()做并在同一个查询中检索它们。

到目前为止,我尝试做的目标是:

  1. 我复制了PIVOT部分并试图做FULL OUTER JOIN,但问题是它正在重复列到最终结果会产生错误(无效的列名)。当我打印@resultado时,它就是,列是重复的。
  2. 
    
    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)
    
    
    

    1. 我尝试了UNPIVOT and PIVOT method,这也会产生无效列错误。

1 个答案:

答案 0 :(得分:1)

所以不用说,做任何动态都是非常有问题的,因为你从来没有真正掌握你的元数据。在任何情况下,当你有多个这样的条件聚合来使用CASE语句来合并你的不同度量时,它更容易接受,比如

    SUM(CASE When Setor = ''' + Setor ''' then 1 else 0 end) 
as [' + Setor + '_Count], 
SUM(CASE When Setor = ''' + Setor ''' then Valor_do_Emprestimo else 0 end) 
as [' + Setor + '_Total],'

只需针对您的数据集以这种方式构建单个查询。

无论如何,要回答您的具体问题,如果您想要将这两者结合起来,您必须提供唯一的列名,这意味着您需要创建稍微不同的@campos和@total版本。在这里,我刚刚完成@campos给你的想法。

注意我还必须在第二个数据透视中将hc_key更改为hc_key2,以避免重复的列名。

declare @campos nvarchar (max)
select @campos  = coalesce(@campos + ',[' + Setor + ']', '[' + Setor + ']')
from dbo.TbFinanciamentos
group by Setor
order by Setor

declare @campos2 nvarchar (max)
select @campos2  = coalesce(@campos2 + ',[' + Setor + '_2]', '[' + Setor + '_2]')
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 * into #temp_total from (
        select *, '+ @total +' as [value]          from
        (
             select * from (select Setor, ''br-'' + lower(UF_FILIAL) as [hc-key] from dbo.TbFinanciamentos) pvt
                 pivot(
                     count([Setor])
                     for Setor in(' + @campos + ')
                 ) as b
             ) as sth
            full outer join
            (
               select *          from (
             select * from (select cast(Valor_do_Emprestimo as float) as Valor_do_Emprestimo, Setor+''_2'' as Setor, ''br-'' + lower(UF_FILIAL) as [hc-key2] from dbo.TbFinanciamentos ) pvt
                 pivot(
                    sum([Valor_do_Emprestimo])
                     for Setor in(' + @campos2 + ')
                 ) as b
             ) c
            ) as sth_else
            on sth.[hc-key] = sth_else.[hc-key2]
         ) d

         select * from #temp_total'
        execute(@resultado)