Sql 多栏透视和求和
我有一个创建以下数据的查询:Sql 多栏透视和求和,sql,sql-server,pivot,Sql,Sql Server,Pivot,我有一个创建以下数据的查询: ID LegacyID type1 type2 date value 1500000001 10070242801000000217 DF RN 2018-05-24 -3.33000000 1500000002 10078387921000000217 PP IN 2018-05-26 -11.00000000 1500000002 100783879210
ID LegacyID type1 type2 date value
1500000001 10070242801000000217 DF RN 2018-05-24 -3.33000000
1500000002 10078387921000000217 PP IN 2018-05-26 -11.00000000
1500000002 10078387921000000217 PP RN 2018-05-26 -100.00000000
1500000003 10080625841000000217 DF RN 2018-05-23 -3.33000000
1500000003 10080625841000000217 DF RN 2018-05-23 99.000000
我试图在类型字段上透视数据,在按ID、LegacyID和date字段分组时求和值
创建此:
id legacyid date DFRN PPIN PPRN
1500000001 10070242801000000217 2018-05-24 -3.33000000 0 0
1500000002 10078387921000000217 2018-05-26 0 -11.00000000 -100.00000000
1500000003 10080625841000000217 2018-05-23 95.67000000 0 0
请注意,我正在尝试将类型字段连接到它们唯一的组合中
我已经尝试了pivot的几种突变,但我似乎无法正确实现,我最近的尝试(无效)如下所示:
select
id,
legacyid,
[date],
[DF]+[RN] as DFRN,
[CR]+[CR] as CRCR,
[CR]+[MR] as CRMR,
[DF]+[DS] as DFDS,
[DF]+[MR] as DFMR,
[PP]+[DS] as PPDS,
[PP]+[IN] as PPIN,
[PP]+[RN] as PPRN,
from (
select
tl.[id],
r.[LegacyId],
a.type1,
bt.type2,
[Date],
gl.TotalAmountUSD as [value]
from
----long join
where
gh.IsActive = 1
group by
tl.id,
r.LegacyId,
a.type1,
bt.type2,
[date])
) as bb
pivot
(
sum(value)
for rentalid in (
[DF]+[RN] as DFRN,
[CR]+[CR] as CRCR,
[CR]+[MR] as CRMR,
[DF]+[DS] as DFDS,
[DF]+[MR] as DFMR,
[PP]+[DS] as PPDS,
[PP]+[IN] as PPIN,
[PP]+[RN] as PPRN)
) as p
如何在这一点上发挥作用?只需使用条件聚合:
with t as (
. . .
)
select ID, LegacyID, date,
sum(case when type1 = 'DF' and type2 = 'RN' then value end) as DFRN,
sum(case when type1 = 'PP' and type2 = 'IN' then value end) as PPIN,
sum(case when type1 = 'PP' and type2 = 'RN' then value end) as PPRN
from t
group by ID, LegacyID, date ;
你试过在派生表中连接type1+type2吗?谢谢你,戈登,像往常一样,很高兴接受你的教育。