简体   繁体   English

SQL Server Pivot总计总计?

[英]SQL Server Pivot with grand total?

I am able to pivot dymaically a tale with my parties from a table, the code below works fine and there's not problem below. 我可以从桌子上与我的聚会动态地讲述一个故事,下面的代码工作正常,下面没有问题。

SELECT @PartiesNames +=  QUOTENAME(LTRIM(RTRIM([Party]))) + ',' 
        FROM table1 WHERE [Party] <> ''
        GROUP BY [Party]

SET @PartiesNames = LEFT(@PartiesNames, LEN(@PartiesNames) - 1)


SET @SQL =
    '
     SELECT * 
     FROM (SELECT 
                  table1.[Party]
                 ,table1.[Accounts]
                 ,[Amount] = FORMAT(SUM(table1.[Amount]),''N0'')
                 FROM  table1

                     GROUP BY table1.[Party]
                    ,table1.[Accounts]
                    ) AS BaseData

    PIVOT(
        MAX(BaseData.[Amount])
        FOR BaseData.[Party]
        IN(' + @PartiesNames + '     
        )
    ) AS PivotTable
    ' 

    EXEC( @SQL)

And I get a normal pivot table but my question, how can I adjust this code to get a new row or/and column with the total? 我得到了一个普通的数据透视表,但我的问题是,如何调整此代码以获取总数的新行或列。 I've been following this article on how to do it but it's qiute tricky to follow: https://www.codeproject.com/Articles/232181/SQL-Pivot-with-Grand-Total-Column-and-Row 我一直在关注如何执行此文章,但要进行以下操作很麻烦: https ://www.codeproject.com/Articles/232181/SQL-Pivot-with-Grand-Total-Column-and-Row

I am open to new solutions on how to solve this problem. 我愿意就如何解决此问题提供新的解决方案。 I believe one reason why this is tricky to solve is because resources online are not very well explained and it does get tricky very fast, anyway I appreciate the support and suggestions. 我相信解决这一难题的原因之一是,由于对在线资源的解释不够好,而且确实很快变得棘手,无论如何,我都非常感谢您的支持和建议。

If interested in a Helper Function. 如果对辅助功能感兴趣。

This Table-Valued Function returns the Count,Sum,Min,Max,Avg and STDev of virtually any row. 这个表值函数返回几乎任何行的Count,Sum,Min,Max,Avg and STDev

All you have to do is add a CROSS APPLY after your PIVOT . 您要做的就是在PIVOT之后添加CROSS APPLY

I should add that you must " EXCLUDE " any numeric column that you DON'T want in the aggregates 我要补充一点,你必须“ 排除 ”任何数值列,你不要在聚集想

Example

Declare @T1 Table ([Branch] varchar(50),[Item] varchar(50),[Sales] int)
Insert Into @T1 Values 
 ('23','Apples',25)
,('23','Coffee',56)
,('23','Bread',22)
,('14','Apples',56)
,('14','Coffee',65)
,('14','Bread',null)


Select Pvt.*
      ,Ttl.*
 From  @T1
 Pivot ( max(Sales) for Item in ([Apples],[Coffee],[Bread]) ) Pvt
 Cross Apply [dbo].[tvf-Stat-Row-Agg]('Branch,OtherColumsToExclude',(Select Pvt.* for XML Raw)) Ttl

Returns 返回

/----     From Pivot    ----\  /----          From CROSS APPLY          ----\  

Branch  Apples  Coffee  Bread   RetCnt  RetSum  RetMin  RetMax  RetAvg  RetStd
14      56      65      NULL    2       121     56      65      60.5    6.3639
23      25      56      22      3       103     22      56      34.33   18.8237

The TVF If Interested TVF如果有兴趣

CREATE FUNCTION [dbo].[tvf-Stat-Row-Agg](@Exclude varchar(500),@XML xml)
Returns Table 
As
Return (  
    Select RetCnt = count(value) 
          ,RetSum = Sum(Value)
          ,RetMin = Min(Value)
          ,RetMax = Max(Value)
          ,RetAvg = Avg(Value)
          ,RetStd = Stdev(Value)
    From  (
            Select Item  = xAttr.value('local-name(.)','varchar(100)')
                  ,Value = try_convert(float,xAttr.value('.','varchar(max)'))
             From  @XML.nodes('//@*') x(xAttr)
          ) S
    Where charindex(','+S.Item+',',','+@Exclude+',')=0
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM