1、数据格式如:
2、sid,mid相同的,只取一条,如ID=1/2/3/4 只取一条
3、只取sid或mid==5的数据
写case when..
select * from 表名 where id in(select max(id) from 表名 group by sid,mid )
with t(id,sid,mid) as (
select 1,4,5
union all select 2,4,5
union all select 3,5,4
union all select 4,5,4
union all select 5,6,5
union all select 6,5,8
union all select 7,5,10
union all select 8,10,5
),t1 as (
select * from t
unpivot(val for col in (sid,mid)) p
)
select * from t a
cross apply(
select STUFF((
select ','+convert(varchar,val)
from t1
where id=a.id
order by val
for xml path('')
),1,1,'') as val
) b
id sid mid val
----------- ----------- ----------- --------------------------
1 4 5 4,5
2 4 5 4,5
3 5 4 4,5
4 5 4 4,5
5 6 5 5,6
6 5 8 5,8
7 5 10 5,10
8 10 5 5,10
(8 行受影响)
自行根据val列排重取结果
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632