【问题标题】:SQL Pivot Group by?SQL Pivot 分组依据?
【发布时间】:2018-10-01 03:02:20
【问题描述】:

我有一个可用的数据透视表,但我想知道是否有办法按数据透视表进行分组。对于我有的数据透视表代码...

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

这也是通过数据透视表完成的,这一点很重要。

谢谢大家的建议!

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    如果您在源查询中将金额设为负数或正数,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;
    

    可以在 RexTester 上找到here 的测试。

    【讨论】:

    • 谢谢!这对我有用!你是 LukStorms 的传奇人物!
    • @OverFlowMars 只是为了完整和提供信息,我已经包含了一个动态 sql 版本。
    【解决方案2】:

    不要为此使用枢轴。只需使用条件聚合:

    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;
    

    【讨论】:

      猜你喜欢
      • 2020-06-09
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多