【发布时间】:2019-07-16 12:32:03
【问题描述】:
我有以下示例数据:
+------------+--------+--------+----------+----------+
| Type | Total1 | Total2 | Account1 | Account2 |
+------------+--------+--------+----------+----------+
| Adjustment | -2.14 | 2.14 | 1220 | 4110 |
| Adjustment | 0.21 | -0.21 | 1220 | 4110 |
| Adjustment | -6.43 | 6.43 | 1220 | 1220 |
+------------+--------+--------+----------+----------+
我要做的是 PIVOT/SUM,其中 Account1 列与 Total1 列相关,Account2 表与 Total2 列相关。
但是在进行透视时,我需要按 Account1 和 Account2 的组合进行透视,并按该帐户代码的相关 Total 列求和,因此使用此示例数据,我得到以下结果:
+------------+-------+------+
| Type | 1220 | 4110 |
+------------+-------+------+
| Adjustment | -1.93 | 1.93 |
+------------+-------+------+
到目前为止,我的两次尝试都包括这个,但它并不完全在那里。有人可以告诉我我缺少什么吗?
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'
【问题讨论】:
标签: sql sql-server tsql