SQL Pivot分组依据?

时间:2018-09-30 16:45:10

标签: sql sql-server

我有一个工作的数据透视表,但是我想知道是否有一种方法可以对数据透视表进行分组。对于数据透视表代码,我有...

SELECT *  FROM 
    (SELECT  
          UserPivot.[parties]
          ,UserPivot.[Accounts]
          ,UserPivot.[CurrentAmount] 
          ,UserPivot.[Plus / Negative]
          FROM UserPivot) AS BaseData

PIVOT(
    SUM(BaseData.[CurrentAmount])
    FOR BaseData.[parties]
    IN([Toms])
) AS PivotTable

运行一次,我得到...

Accounts | Plus / negative | Toms
Bank             plus         100
Bank           negative        60

以上是正确的,我需要[plus / negative]列来显示用户正在进行的所有操作!但我要添加一个分组以显示一个帐户的总和,并按不同的帐户类型对其进行分组,例如,我想要以下结果...

   Accounts  | Toms
    Bank        40

同样重要的是,还要通过数据透视表完成此操作。

谢谢大家的建议!

2 个答案:

答案 0 :(得分:0)

请勿为此使用数据透视。只需使用条件聚合:

SELECT UserPivot.Accounts,
       SUM(CASE WHEN UserPivot.[Plus / Negative] = 'plus' THEN UserPivot.CurrentAmount
                WHEN UserPivot.[Plus / Negative] = 'negative' THEN 
- UserPivot.CurrentAmount
           END) as net_amount
FROM UserPivot
GROUP BY UserPivot.Accounts;

答案 1 :(得分:0)

如果在源查询中将金额设置为负数或正数,SUM将使用它。

SELECT *  
FROM 
(
  SELECT [Accounts],
  [parties],
  IIF([Plus / Negative] = 'negative', -[CurrentAmount], [CurrentAmount]) AS [CurrentAmount]
  FROM UserPivot
  WHERE [parties] IN ('Toms') -- This WHERE clause is just something that could increase performance of the query
) AS BaseData
PIVOT(
    SUM([CurrentAmount]) 
    FOR [parties]
    IN([Toms])
) AS PivotTable;

如果您不想对所有各方进行硬编码。
您可以为此使用动态SQL。

declare @Cols nvarchar(1000); -- A list of the columns for the pivot
select @Cols = concat(@Cols+',', quotename([parties])) from UserPivot group by [parties];

declare @DynSql nvarchar(2000) = 'SELECT *  
FROM 
(
  SELECT [Accounts],
  [parties],
  IIF([Plus / Negative] = ''negative'', -[CurrentAmount], [CurrentAmount]) AS [CurrentAmount]
  FROM UserPivot
) AS BaseData
PIVOT(
    SUM([CurrentAmount]) 
    FOR [parties]
    IN('+ @Cols +')
) AS PivotTable';

EXECUTE sp_executesql @DynSql;

可以在{x3}}上的RexTester中找到对这两者的测试。