简体   繁体   English

根据特定值创建新列另一列

[英]create new column based on specific values another columns

Let say I have this kind of column假设我有这种专栏

create table exercise (cust_id varchar, policy_id varchar, end_date date, flag varchar);   
insert into exercise (cust_id, policy_id, end_date, flag)
values
('1', 'a1', '2022-10-12', 'inactive'),
('1', 'a2', '2022-10-20', 'inactive'),
('1', 'a2', '2023-05-15', 'active'),
('2', 'a3', '2022-12-12', 'inactive')
('3', 'a3', '2022-09-18', 'inactive')
('3', 'a1', '2023-12-22', 'active')

from that column, we know that 3 customers (1, 2, 3) with 3 products(a1, a2, a3)从该列中,我们知道 3 个客户(1、2、3)有 3 个产品(a1、a2、a3)
Is there any way to make new column,有没有办法制作新专栏,
if the customer have flag 'active' and 'inactive' then it called 'good',如果客户有标志“活跃”和“不活跃”那么它叫做“好”,
but if the customer only have flag 'inactive' then it called 'bad'但如果客户只有“不活动”标志,则它称为“坏”

so the output will be look like this, how the logic???所以 output 看起来像这样,逻辑如何???

cust_id客户编号 policy_id保单编号 end_date结束日期 flag旗帜 credit信用
1 1个 a1 a1 2022-10-12 2022-10-12 inactive不活跃 good好的
1 1个 a2 a2 2022-10-20 2022-10-20 inactive不活跃 good好的
1 1个 a2 a2 2023-05-15 2023-05-15 active积极的 good好的
2 2个 a3 a3 2022-12-12 2022-12-12 inactive不活跃 bad坏的
3 3个 a3 a3 2022-09-18 2022-09-18 inactive不活跃 good好的
3 3个 a1 a1 2023-12-22 2023-12-22 active积极的 good好的

We can use COUNT() here as a window function, along with conditional aggregation:我们可以在这里使用COUNT()作为 window function,以及条件聚合:

SELECT cust_id, policy_id, end_date, flag,
       CASE WHEN COUNT(CASE WHEN flag = 'active' THEN 1 END)
                     OVER (PARTITION BY cust_id) > 0
            THEN 'good' ELSE 'bad' END AS credit
FROM exercise
ORDER BY cust_id, end_date;

Try this :试试这个

SELECT *
      ,CASE WHEN MAX(CASE WHEN flag = 'inactive' THEN 1 END) OVER (PARTITION BY cust_id) = 1 AND MAX(CASE WHEN flag = 'active' THEN 1 END) OVER (PARTITION BY cust_id) = 1 THEN 'good' ELSE 'bad' END
FROM exercise 

we can use inner join as follows:我们可以使用inner join如下:

This one take on consideration if the last order is active or not.如果最后一个订单处于活动状态,则需要考虑这一点。

Example if the last order of a customer is inactive he should be considered as bad customer:例如,如果客户的最后一个订单处于非活动状态,则他应被视为不良客户:

SELECT *, CASE WHEN s.flag = 'active' THEN 'good' ELSE 'bad' END as credit
FROM exercise t
join (
  SELECT t.cust_id, t.flag
  FROM (
      select cust_id, max(end_date) as max_date
      from exercise
      group by cust_id
  ) r
  INNER JOIN exercise t
  ON t.cust_id = r.cust_id AND t.end_date = r.max_date
) as s on s.cust_id = t.cust_id

check it here: https://dbfiddle.uk/j0TtG62a在这里查看: https://dbfiddle.uk/j0TtG62a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM