从TableName中选择*
从此:
ID Col1 Col2 Col3 Col4 Col5
1 aa 21 ss m p
2 aa 21 tt f u
3 bb 21 ss f d
4 bb 22 ss m d
到这个
ID Col1 Col2 Col3 Col4 Col5
1 aa 21 ss m p
2 tt f u
3 bb ss d
4 22 m
我希望这个输出有可能吗?
如果它位于相同的
旁边,则不要重复重复值感谢您的时间。
答案 0 :(得分:1)
请检查查询,这是您需要的吗?:
update a set
a.Col1=(case when cnt1=1 then a.Col1 else null end),
a.Col2=(case when cnt2=1 then a.Col2 else null end),
a.Col3=(case when cnt3=1 then a.Col3 else null end)
from TableName a
join
(
select *,
row_number() over (Partition By Col1 order by ID) cnt1,
row_number() over (Partition By Col2 order by ID) cnt2,
row_number() over (Partition By Col3 order by ID) cnt3
From TableName
) x on a.ID=x.ID
答案 1 :(得分:1)
您可以选择要临时表的所有内容,清除重复的值并从更新的临时表中返回结果集。
查询可能如下所示:
select 1 as id, 'aa' as col1, '21' as col2,'ss' as col3,'m' as col4,'p' as col5 into #tmp union
select 2, 'aa','21','tt','f','u' union
select 3, 'bb','21','ss','f','d' union
select 4, 'bb','22','ss','m','d'
update t set
col1 = case when tp.col1 = t.col1 then '' else t.col1 end,
col2 = case when tp.col2 = t.col2 then '' else t.col2 end,
col3 = case when tp.col3 = t.col3 then '' else t.col3 end,
col4 = case when tp.col4 = t.col4 then '' else t.col4 end,
col5 = case when tp.col5 = t.col5 then '' else t.col5 end
from #tmp t
left join (
select t1.id, max(t2.id) as pid
from #tmp t1
join #tmp t2 on t1.id > t2.id
group by t1.id
) p on t.id = p.id
left join #tmp tp on p.pid = tp.id
结果:
/*------------------------
select top 100 * from #tmp
------------------------*/
id col1 col2 col3 col4 col5
1 aa 21 ss m p
2 tt f u
3 bb ss d
4 22 m