在多个列上进行多次求和

时间:2019-07-16 12:32:03

标签: sql sql-server tsql

我有以下示例数据。

enter image description here

我要做的是PIVOT / SUM,其中Account1列与Total1列相关,而Account2表与Total2列相关。

但是,在进行透视时,我需要按Account1和Account2的总和进行透视,并按该账户代码的相关“总计”列求和,因此对于此示例数据,我得出以下结果:

enter image description here

到目前为止,我的两次尝试都包括这一点,但是还不足够。有人可以告诉我我所缺少的吗?

select
 Type,
 sum([1220]) as [1220],
 sum([4110]) as [4110]
 from 
 #temp
    pivot
    (
      sum(Total1)
      for Account1 in ([1220],[4110])
    ) p
group by
    Type

select
 Type,
 sum(case When Account1 = '1220' Then Total1 WHEN Account2 = '1220' Then Total2 end) as [1220],
 sum(case When Account1 = '4110' Then Total1 WHEN Account2 = '4110' Then Total2 end) as [4110]
 from 
 #temp
group by
    Type

样本数据

CREATE TABLE #temp
(
Type varchar(50),
Total1 money,
Total2 money,
Account1 int,
Account2 int
)

insert into #temp
(
Type,
Total1,
Total2,
Account1,
Account2
)

select
'Adjustment',
'-2.14',
'2.14',
'1220',
'4110'

union all

select
'Adjustment',
'0.21',
'-0.21',
'1220',
'4110'

union all

select
'Adjustment',
'-6.43',
'6.43',
'1220',
'1220'

2 个答案:

答案 0 :(得分:3)

我们可以尝试采用联合方法来解决此问题:

WITH cte AS (
    SELECT [Type], Total1 AS Total, Account1 AS Account FROM #temp
    UNION ALL
    SELECT [Type], Total2, Account2 FROM #Temp
)

SELECT
    [Type],
    SUM(CASE WHEN Account = '1220' THEN Total ELSE 0 END) AS [1220],
    SUM(CASE WHEN Account = '4110' THEN Total ELSE 0 END) AS [4110]
FROM cte
GROUP BY
    Type;

enter image description here

Demo

这里的基本策略是将所有帐户和总计放入两个单独的列中,然后在这些单个列上进行汇总/数据透视。可以解决要跨多个列聚合的数据的问题。最好的长期解决方法可能是将您的数据结构更改为仅一个用于帐户和总计的列。

答案 1 :(得分:2)

另一种选择是使用CROSS APPLYUNPIVOT您的数据,然后使用 PIVOT

示例

Select *
 From  (
        Select A.[Type] 
              ,B.*
         from #Temp A
         Cross Apply ( values (Total1,Account1)
                             ,(Total2,Account2)
                     ) B (Value,Item)
       ) Src
 Pivot (sum(Value) for Item in ([1220],[4110]) ) pvt

返回

Type        1220    4110
Adjustment  -1.93   1.93