检查另一列中每行的值是不是相同
Posted
技术标签:
【中文标题】检查另一列中每行的值是不是相同【英文标题】:Check if values are the same for each row over a critiera in another column检查另一列中每行的值是否相同 【发布时间】:2021-12-30 10:47:24 【问题描述】: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');
预期结果:
campaign | supplier | plan_quantity | check |
----------|--------------|-------------------|----------------|-------
C001 | supplier_a | 500 | same |
C001 | supplier_a | 500 | same |
C001 | supplier_b | 500 | same |
----------|--------------|-------------------|----------------|-------
C002 | supplier_a | 600 | different |
C002 | supplier_b | 700 | different |
----------|--------------|-------------------|----------------|-------
C003 | supplier_c | 100 | same |
C003 | supplier_c | 100 | same |
----------|--------------|-------------------|----------------|-------
C004 | supplier_a | 900 | different |
C004 | supplier_c | 800 | different |
C004 | supplier_d | 250 | different |
C004 | supplier_d | 250 | different |
在结果中的check
列中,我想查看每个supplier
和campaign
的plan_quantity
是否相同。
如果是,则应写为same
,否则应写为different
。
SELECT
campaign AS campaign,
supplier AS supplier,
plan_quantity AS plan_quantity,
(CASE WHEN plan_quantity for each supplier per campaign is the same THEN 'same' else 'different' END) AS check
FROM campaigns
ORDER BY 1,2,3;
我不知道我需要什么功能才能让它工作。 你有什么想法吗?
【问题讨论】:
【参考方案1】:您可以使用窗口分析函数来检查值:
select *,
case when
Min(plan_quantity) over(partition by campaign)
= Max(plan_quantity) over(partition by campaign)
then 'same' else 'different'
end as "Check"
from campaigns
【讨论】:
【参考方案2】:您可以使用窗口max
和min
SELECT
campaign AS campaign,
supplier AS supplier,
plan_quantity AS plan_quantity,
CASE WHEN max(plan_quantity) over(partition by supplier, campaign) = min(plan_quantity) over(partition by supplier, campaign) THEN 'same' ELSE 'different' END AS check
FROM campaigns
ORDER BY 1,2,3;
【讨论】:
它在每一行都放置“相同”。 你的措辞模棱两可。尝试从partition
子句中删除supplier,
【参考方案3】:
您可以通过按campaign
分组来找出哪个campaign
具有唯一的plan_quantity
,并简单地计算不同的plan_quantity
SELECT
campaign AS campaign
FROM campaigns
GROUP BY campaign
HAVING COUNT(DISTINCT plan_quantity) = 1
这样你就可以做你想做的事了。以连接为例:
SELECT
campaigns.campaign,
supplier,
plan_quantity,
CASE WHEN grouping IS NOT NULL THEN 'same' ELSE 'different' END as check
FROM campaigns
LEFT JOIN (
-- Get all campaign with same plan_quantity
SELECT
campaign
FROM campaigns
GROUP BY campaign
HAVING COUNT(DISTINCT plan_quantity) = 1
) as grouping
ON campaigns.campaign = grouping.campaign
【讨论】:
以上是关于检查另一列中每行的值是不是相同的主要内容,如果未能解决你的问题,请参考以下文章
检查一列中的值是不是存在于另一列中,如果存在,则将另一列中的值复制到新列中