检查每个广告系列在一个国家/地区的销售状态是不是已更改,并将其分配给结果中每个广告系列的所有国家/地区
Posted
技术标签:
【中文标题】检查每个广告系列在一个国家/地区的销售状态是不是已更改,并将其分配给结果中每个广告系列的所有国家/地区【英文标题】:Check if sales-status in one country per campaign has changed and assign it to all countries per campaign in the results检查每个广告系列在一个国家/地区的销售状态是否已更改,并将其分配给结果中每个广告系列的所有国家/地区 【发布时间】:2020-09-16 09:59:03 【问题描述】:DB-Fiddle:
CREATE TABLE operations (
id int auto_increment primary key,
campaign VARCHAR(255),
country VARCHAR(255),
sales_status VARCHAR(255),
quantity INT
);
INSERT INTO operations
(campaign, country, sales_status, quantity
)
VALUES
("C001", "DE", "demand", "100"),
("C001", "US", "shipped", "300"),
("C001", "NL", "shipped", "700"),
("C001", "FR", "shipped", "400"),
("C002", "DE", "demand", "500"),
("C002", "US", "demand", "900"),
("C002", "FR", "shipped", "200"),
("C003", "US", "demand", "600"),
("C003", "NL", "demand", "250"),
("C003", "FR", "demand", "150"),
("C003", "PL", "demand", "550"),
("C004", "DE", "shipped", "825"),
("C004", "PL", "shipped", "462");
预期结果:
campaign | country | sales_status | quantity
---------|-----------|-----------------|------------------
C001 | DE | shipped | 100
C001 | FR | shipped | 400
C001 | NL | shipped | 700
C001 | US | shipped | 300
| |
C002 | DE | shipped | 500
C002 | FR | shipped | 200
C002 | US | shipped | 900
| | |
C003 | FR | demand | 150
C003 | NL | demand | 250
C003 | PL | demand | 550
| | |
C004 | DE | shipped | 250
C004 | PL | shipped | 550
在上表中,您可以看到不同的campaigns
及其sales_staus
每country.
现在,在结果中,我想要实现,如果 one country
per campaign
在 sales_status
shipped 其他国家应该也可以切换到sales_status
已发货。
例如在C002
国家/地区FR
在sales_status
已发货。
因此,所有其他 countries
在结果中都从 demand 更改为 shipped。
我尝试了这个查询,但无法正常工作:
SELECT
campaign,
country,
(CASE WHEN MIN(sales_status) OVER (PARTITION BY country) = MAX(sales_status) OVER (PARTITION BY country)
THEN MIN(sales_status) ELSE MAX(sales_status) END) AS sales_status,
quantity
FROM operations
GROUP BY 1,2;
我需要进行哪些更改才能获得预期的结果?
【问题讨论】:
【参考方案1】:如果每个广告系列的一个国家/地区处于 sales_status 已发货,则其他所有国家/地区也应切换为 sales_status 已发货。
您可以使用窗口函数和case
表达式:
select
campaign,
country,
case when max(sales_status = 'shipped') over(partition by campaign) = 1
then 'shipped'
else sales_status
end as sales_status,
quantity
from operations
【讨论】:
dbfiddle.uk/…以上是关于检查每个广告系列在一个国家/地区的销售状态是不是已更改,并将其分配给结果中每个广告系列的所有国家/地区的主要内容,如果未能解决你的问题,请参考以下文章