REDSHIFT:根据另一列中的特定值更改列中的值

REDSHIFT: Change value in column based on a certain value in another column

DB-Fiddle

CREATE TABLE customers (
    id SERIAL PRIMARY KEY,
    order_date DATE,
    country VARCHAR(255),
    customer VARCHAR(255)
);

INSERT INTO customers
(order_date, country, customer)
VALUES 
('2020-04-10', 'DE', 'user_01'),
('2020-04-11', 'DE', 'user_01'),
('2020-04-13', 'AT', 'user_01'),

('2020-04-20', 'AT', 'user_02'),
('2020-04-22', 'AT', 'user_02'),

('2020-05-19', 'DE', 'user_03'),

('2020-06-17', 'AT', 'user_04'),
('2020-06-23', 'AT', 'user_04'),
('2020-07-04', 'DE', 'user_04'),

('2020-08-19', 'NL', 'user_05'),
('2020-10-23', 'FR', 'user_05');

预期结果:

order_date   |   customer  |      country     |  
-------------|-------------|------------------|--------------------------------
2020-04-10   |   user_01   |       DE         |        
2020-04-11   |   user_01   |       DE         |       
2020-04-13   |   user_01   |       DE         |  --> country changed to DE 
-------------|-------------|------------------|--------------------------------   
2020-04-20   |   user_02   |       AT         |        
2020-04-22   |   user_02   |       AT         |       
-------------|-------------|------------------|-------------------------------- 
2020-05-19   |   user_03   |       DE         |      
-------------|-------------|------------------|--------------------------------
2020-06-17   |   user_04   |       DE         |  --> country changed to DE 
2020-06-23   |   user_04   |       DE         |  --> country changed to DE
2020-07-04   |   user_04   |       DE         |     
-------------|-------------|------------------|--------------------------------
2020-08-19   |   user_05   |       NL         |     
2020-10-23   |   user_05   |       FR         |      

在上面的例子中,可能有一位顾客在 DEAT 都下了订单。
对于这些客户,我想将 country 列中的国家 DE 分配给他们的每个 order_dates.

参考 的其中一个答案,我尝试这样做:

SELECT
c.order_date AS order_date,
c.customer AS customer,

(CASE WHEN COUNT(*) FILTER (WHERE c.country = 'DE') OVER (PARTITION BY c.customer) > 0
      THEN 'DE' ELSE c.country
      END) AS country
      
FROM customers c
ORDER BY 1,2,3;

但是,在 redshiftFILTER 功能不可用。
我必须如何修改查询才能使其在 redshift 中也能正常工作?

SUM(CASE WHEN c.country = 'DE' THEN 1 END) OVER (PARTITION BY c.customer)

这在 分析函数中使用 CASE 表达式 来应用过滤。

  • 任何不符合条件的东西 returns a NULL
  • 聚合有效跳过NULL

DB Fiddle With Both Approaches