SQL SERVER 多表联查数据去重
时间: 2023-11-23 13:53:12 浏览: 212
SQL SERVER 多表联查数据去重可以通过使用复杂表连接查询实现。具体步骤如下:
1. 单独查出需要关联的多个表,并根据关联主键进行分组排序。
2. 将这些表关联成一个临时表。
3. 最后将临时表与主表进行关联,去除重复数据。
具体实现可以参考以下SQL语句:
with Patent as (select row_number() over(partition by StProjecZtbId order by StProjecZtbId) rowNumber,StProjecZtbId,PatentName from STPatent),
Thesis as(select row_number() over(partition by StProjecZtbId order by StProjecZtbId) rowNumber,StProjecZtbId,ThesisName from STThesis),
Other as(select row_number() over(partition by StProjecZtbId order by StProjecZtbId) rowNumber,StProjecZtbId,[Name] from STOther)
select st.Id,st.StProjectName,T.* from StProjec st
left join (select isnull(Patent.StProjecZtbId,isnull(Thesis.StProjecZtbId,Other.StProjecZtbId)) StProjecZtbId,PatentName,ThesisName,Other.[Name]
from Patent full join Thesis on Patent.rowNumber = Thesis.rowNumber and Patent.StProjecZtbId = Thesis.StProjecZtbId
full join Other on Patent.rowNumber = Other.rowNumber and Patent.StProjecZtbId = Other.StProjecZtbId) T on st.Id=T.StProjecZtbId
where 1=1 order by StProjecZtbId
阅读全文