这张表里有客户身份证号,卡号,发卡日期,卡状态,一个客户名下有多张卡,这些卡既有A又有非A,我的需求是:名下有A状态卡的客户只保留A状态卡的记录,名下都没有A状态卡的客户,只保留最新一张卡的记录
要写表结构出来,才能写对应的SQL语句。
可以将需求拆开,弄成两个sql取数,然后union all 到一起。没有A状态的,可以通过开窗取最新的一条数据,具体写法如下,字段是我根据业务虚拟的名字:
select [明细字段] from user_card_info a where a.card_type = 'A'
union all
select [明细字段] from (
select [明细字段] ,row_number()over(partition by user_id order by deal_time desc ) rn
from user_card_info b
where not exists (select 1 from user_card_info a where a.user_id = b.user_id ) ) cc where cc.rn = 1 ;
希望可以帮到你。