我想将宽数据转换为长数据/将列(c_lead和mkt_bwon)转置为行
具体来说,我想将c_lead和mkt_bwon列转换为行,其中实际值,目标和差异分别具有c_lead和mkt_bwon等行。
因此,为每个“行名”标记为mkt_bwon的各个行。
select
'actuals' as row_name,
cast(period_to as datetime) as time_period,
--determinant,
--sale_location,
--region,
coalesce(leads,0) as leads,
coalesce(opportunities,0) as opps,
coalesce(b_won,0) as bwon,
coalesce(cast(total_spend as decimal(18,2)),0) as t_spend,
coalesce(discount_total,0) as disc,
(t_spend+disc) as t_cost,
(t_spend/leads) as c_lead,
(t_spend/bwon) as mkt_bwon
from
periscope_views.salesforce_deepdive
where
determinant = 'online'
union all
select 'targets' as row_name,
date as time_period,
coalesce(leads, 0) as leads,
coalesce(opps, 0) as opps,
coalesce(won, 0) as bwon,
coalesce(spend, 0) as t_spend,
coalesce(discount, 0) as t_disc,
(t_spend+t_disc) as t_cost,
(t_spend/leads) as c_lead,
(t_spend/bwon) as mkt_bwon
from periscope_views.targets_csv2019
where source = 'online'
union all
select
'difference',
time_period,
sum(leads) as leads,
sum(opps) as opps,
sum(bwon) as bwon,
sum(t_spend) as t_spend,
sum(disc) as disc,
sum(total_cost) as t_cost,
sum(c_lead) as c_lead,
sum(mkt_bwon) as mkt_bwon
from
(
select
'actuals' as row_name,
cast(period_to as datetime) as time_period,
--determinant,
--sale_location,
--region,
coalesce(leads,0) as leads,
coalesce(opportunities,0) as opps,
coalesce(b_won,0) as bwon,
coalesce(cast(total_spend as decimal(18,2)),0) as t_spend,
coalesce(discount_total,0) as disc,
(total_spend+discount_total) as total_cost,
(t_spend/leads) as c_lead,
(t_spend/bwon) as mkt_bwon
from
periscope_views.salesforce_deepdive
where
determinant = 'online'
union all
select 'targets' as row_name,
date as time_period,
coalesce(leads, 0)*-1 as leads,
coalesce(opps, 0)*-1 as opps,
coalesce(won, 0)*-1 as bwon,
coalesce(spend, 0)*-1 as t_spend,
coalesce(discount, 0)*-1 as t_disc,
(t_spend+t_disc)*-1 as t_cost,
(t_spend/leads)*-1 as c_lead,
(t_spend/bwon)*-1 as mkt_bwon
from periscope_views.targets_csv2019
where source = 'online'
)
group by time_period,row_name
order by time_period desc
差异部分应该用于简单计算实际值与目标值之间的差异