我有每年的销售渠道成本表(T):ch=渠道(bo=后台).

YYYY . CH   COST
=====+====+======
2022 . c1 .  20
2022 . c2 .  30
2022 . bo .  50
2023 . c1 .  25
2023 . c2 .  40
2023 . bo .  80

后台成本(ch=bo)应根据分配表(D)中的系数分配给其他销售渠道:

CH . BO_PERC
===+========
c1 .   0.2    <- 20% from BO cost should be added to c1 channel cost (per year)
c2 .   0.4    <- 40% from BO cost should be added to c2 channel cost (per year)

生成的表格应该如下所示:

YYYY . CH . COST
=====+====+=====
2022 . c1 .  30     <- 20 + 50*0.2
2022 . c2 .  50     <- 30 + 50*0.4
2023 . c1 .  41     <- 25 + 80*0.2
2023 . c2 .  72     <- 40 + 80*0.4

如何得到将年度BO成本分配到其他渠道的结果表?

推荐答案

您需要处理您的表名和列名.除了它们太短和非描述性之外,BO_PERC实际上是错误的:它没有以百分比的形式存储.

以下查询输出预期结果:

create table channel_costs(
  year smallint not null check(year between 1900 and 2200),
  channel varchar(2) not null,
  cost money not null check (cost > cast(0 as money))
);

insert into channel_costs(year, channel, cost) values
(2022, 'c1',  20),
(2022, 'c2',  30),
(2022, 'bo',  50),
(2023, 'c1',  25),
(2023, 'c2',  40),
(2023, 'bo',  80);

create table distribution(
  channel varchar(2) not null,
  backoffice_fraction real not null check(backoffice_fraction between 0 and 1)
);

insert into distribution(channel, backoffice_fraction) values
('c1', 0.2),
('c2', 0.4);

select front_costs.year,
       front_costs.channel,
       front_costs.cost + distribution.backoffice_fraction * back_costs.cost as cost
from channel_costs as front_costs
join channel_costs as back_costs on back_costs.year = front_costs.year
                                and back_costs.channel = 'bo'
                                and front_costs.channel <> 'bo'
join distribution on distribution.channel = front_costs.channel
order by front_costs.year, front_costs.channel;

Sql相关问答推荐

如何并行SELECT和RESET?

从2个表中查找每条记录的唯一最接近的日期匹配

当我们加入两个表时,我们可以省略GROUP BY中的列名吗?

我可以将INSERT语句与SELECT一起使用来创建条件吗?

在甲骨文中查找前一个星期一的S日期

在Postgres中实现合并功能的干净方法,因为当目标/源不匹配时

计算分段的总权重

更新PostgreSQL 15中的JSON值

替换上一个或下一个值中的空值并添加其价格日期

来自按PostgreSQL分组的最小日期

PATINDEX中与[A-Z]匹配(U除外)的正则表达式

使用与JOIN一起使用的查询后进行分页和排序

更新之前如何获得价值

函数调用作为插入值语句中的参数

连续期间的缺口

超过100名员工的连续行

SQL - 使用子查询返回多行的 LIKE 命令

来自 SQL Server 的树层次 struct 图的 JSON

从不同的表中 Select 包含单词列表的记录

在 SQL 中将行显示为列