检查不同其他列中每行的值是不是相同
Posted
技术标签:
【中文标题】检查不同其他列中每行的值是不是相同【英文标题】:Check if values are the same for each row over criteria in different other columns检查不同其他列中每行的值是否相同 【发布时间】:2021-12-30 11:33:13 【问题描述】:DB-Fiddle
CREATE TABLE campaigns
(
id SERIAL PRIMARY KEY,
campaign VARCHAR,
supplier VARCHAR,
plan_quantity DECIMAL
);
INSERT INTO campaigns (campaign, supplier, plan_quantity)
VALUES ('C001', 'supplier_a', '500'),
('C001', 'supplier_a', '500'),
('C001', 'supplier_b', '500'),
('C002', 'supplier_a', '600'),
('C002', 'supplier_b', '700'),
('C003', 'supplier_c', '100'),
('C003', 'supplier_c', '100'),
('C004', 'supplier_a', '900'),
('C004', 'supplier_c', '800'),
('C004', 'supplier_d', '250'),
('C004', 'supplier_d', '250'),
('C005', 'supplier_b', '380'),
('C005', 'supplier_b', '270'),
('C005', 'supplier_d', '590');
预期结果:
campaign | supplier | plan_quantity | check |
----------|--------------|-------------------|--------------------|-------
C001 | supplier_a | 500 | same |
C001 | supplier_a | 500 | same |
C001 | supplier_b | 500 | non-relevant |
----------|--------------|-------------------|--------------------|-------
C002 | supplier_a | 600 | non-relevant |
C002 | supplier_b | 700 | non-relevant |
----------|--------------|-------------------|--------------------|-------
C003 | supplier_c | 100 | same |
C003 | supplier_c | 100 | same |
----------|--------------|-------------------|--------------------|-------
C004 | supplier_a | 900 | non-relevant |
C004 | supplier_c | 800 | non-relevant |
C004 | supplier_d | 250 | same |
C004 | supplier_d | 250 | same |
----------|--------------|-------------------|--------------------|-------
C005 | supplier_b | 380 | different |
C005 | supplier_b | 270 | different |
C005 | supplier_d | 590 | non-relevant |
如果供应商在每个广告系列中出现多次,我想在check
列中查看该供应商的plan_quantity
是否在每一行中都相同。
当我从this question修改查询时,我已经接近结果了:
SELECT
campaign AS campaign,
supplier AS supplier,
plan_quantity AS plan_quantity,
(CASE
WHEN MIN(plan_quantity) OVER (PARTITION BY supplier, campaign) = MAX(plan_quantity) OVER (PARTITION BY supplier, campaign)
THEN 'same'
ELSE 'different'
END) AS check
FROM
campaigns
ORDER BY
1, 2, 3;
但是,我不知道如何添加与查询无关的描述,以防供应商在每个广告系列中没有出现多次。
你有什么想法吗?
【问题讨论】:
【参考方案1】:您可以使用附加的 case 表达式 稍微修改查询,以便检查何时 same 并指示任何计数为 1 的内容不相关:
select
campaign,
supplier,
plan_quantity,
case when
Min(plan_quantity) over(partition by campaign, supplier)
= Max(plan_quantity) over(partition by campaign, supplier)
then
case when Count(*) over(partition by campaign, supplier) = 1
then 'non-relevant' else 'same'
end
else 'different'
end as Check
from campaigns
order by 1,2,3;
【讨论】:
仅用于我的文档:dbfiddle.uk/…以上是关于检查不同其他列中每行的值是不是相同的主要内容,如果未能解决你的问题,请参考以下文章