表的行列转置

本文介绍了一种使用SQL进行复杂数据聚合的方法,通过左连接及CASE WHEN语句实现不同条件下的计数,并进一步将计数结果进行转置处理,以便于数据展示和分析。此外还展示了如何按客户等级汇总特定原因的数量。

原始数据:

select t1.CarModelPKID,t2.DefeatReason, count(*) as count from RT_CustAllocResult t
left join vm_carinfo t1 on t1.FrameNo = t.FrameNo
left join RT_CustFollowUp t2 on t2.RegNo = t.RegNo
where t1.CarModelPKID is not null and t2.DefeatReason is not null group by t2.DefeatReason,CarModelPKID

转置后的数据:

select t.CarModelPKID,
case DefeatReason when '00' then count end as colReason1,
case DefeatReason when '01' then count  end as colReason2,
case DefeatReason when '02' then count  end as colReason3,
case DefeatReason when '03' then count  end as colReason4,
case DefeatReason when '04' then count  end as colReason5,
case DefeatReason when '05' then count  end as colReason6,
case DefeatReason when '06' then count  end as colReason7,
case DefeatReason when '07' then count  end as colReason8,
case DefeatReason when '08' then count  end as colReason9

from(select t1.CarModelPKID,t2.DefeatReason, count(*) as count from RT_CustAllocResult t
left join vm_carinfo t1 on t1.FrameNo = t.FrameNo
left join RT_CustFollowUp t2 on t2.RegNo = t.RegNo
where t1.CarModelPKID is not null and t2.DefeatReason is not null group by t2.DefeatReason,CarModelPKID) t 

数据统计:

select t.CustomerLevel as Item,
sum(case DefeatReason when '00' then count end) as colReason1,
sum(case DefeatReason when '01' then count end) as colReason2,
sum(case DefeatReason when '02' then count end) as colReason3,
sum(case DefeatReason when '03' then count end) as colReason4,
sum(case DefeatReason when '04' then count end) as colReason5,
sum(case DefeatReason when '05' then count end) as colReason6,
sum(case DefeatReason when '06' then count end) as colReason7,
sum(case DefeatReason when '07' then count end) as colReason8,
sum(case DefeatReason when '08' then count end) as colReason9

from(select t.CustomerLevel,t2.DefeatReason, count(*) as count from RT_CustAllocResult t
left join RT_CustFollowUp t2 on t2.RegNo = t.RegNo
where t.CustomerLevel is not null and t2.DefeatReason is not null 
group by t2.DefeatReason,t.CustomerLevel) t  group by t.CustomerLevel

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值