求大神,sql,只有A时保留A,其他情况下剔除A

ivanmalasan 2020-06-28 10:37:00
一张表,同一user_id多次不同渠道进入,要求是当user_id 唯一通过A渠道进入时保留该user_id首次通过A时的记录,其他情况下,剔除通过A渠道进入的记录。
表:
user_id channel dt
1 A 2020/6/28
1 A 2020/6/29
2 A 2020/6/30
2 V 2020/7/1
3 A 2020/7/2
3 S 2020/7/3
3 V 2020/7/4

最后效果
user_id channel dt
1 A 2020/6/28
2 V 2020/7/1
3 S 2020/7/3
3 V 2020/7/4
...全文
59 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
RINK_1 2020-06-28
  • 打赏
  • 举报
回复

SELECT *
FROM TABLE A
WHERE NOT EXISTS 
(SELECT 1 FROM TABLE WHERE USER_ID=A.USER_ID AND CHANEL<>'A')
AND NOT EXISTS (SELECT 1 FROM TABLE WHERE USER_ID=A.USER_ID AND DT<A.DT )
UNION ALL
SELECT *
FROM TABLE A
WHERE EXISTS 
(SELECT 1 FROM TABLE WHERE USER_ID=A.USER_ID AND CHANEL<>'A')
AND CHANEL<>'A'
JC34172425 2020-06-28
  • 打赏
  • 举报
回复

create table test(user_id int ,channel varchar(100),dt datetime)
insert into test(user_id,channel,dt)
select 1,'A','2020/6/28'
union select 1 ,'A', '2020/6/29'
union select 2, 'A','2020/6/30'
union select 2, 'V','2020/7/1'
union select 3,'A','2020/7/2'
union select 3, 'S','2020/7/3'
union select 3,'V','2020/7/4'


select a.user_id,a.channel,a.dt from (
select ROW_NUMBER() over(partition by user_id order by user_id,channel,dt) rownum,* from test a
)a 
where rownum=1 and  user_id not in (select user_id from test a where channel<>'A' group by user_id )
union
select * from test a 
where user_id in (select user_id from test a where channel<>'A' group by user_id )
and a.channel<>'A'

向阳的花儿 2020-06-28
  • 打赏
  • 举报
回复


--创建测试数据
create table nota (user_id int, channel varchar(10), dt date)
insert into nota
values(1 ,'A', '2020/6/28'),
(1, 'A' ,'2020/6/29'),
(2, 'A', '2020/6/30'),
(2, 'V', '2020/7/1'),
(3, 'A' ,'2020/7/2'),
(3 ,'S', '2020/7/3'),
(3, 'V', '2020/7/4')
--查询最终数据
with nota_a as --- 唯一通过A渠道进入时保留该user_id首次通过A时的记录
(
select top 1 * from nota where user_id in (
select user_id from nota group by user_id having count(distinct channel)=1)and channel='A' order by dt 
)
,nota_na as   ---- 除掉上一种情况的,都删除渠道A
(
select * from nota where user_id not in (select user_id from nota_a) and channel<>'A'
)
,last_info as ----以上两种情况合并
(select * from nota_a union all select * from nota_na)

--根据查询出来的表更新到原表中
merge into nota as t
using last_info as s
on s.user_id=t.user_id and s.channel=t.channel and s.dt=t.dt
when not matched by source 
then delete;


22,210

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧