我有此输入表:
+-------------+--------------+-------+
| ProjectName | ProjectOwner | Col2 |
+-------------+--------------+-------+
| A | Sara | Sara |
| B | Jack | Maria |
| B | Jack | Jack |
| C | Laura | May |
| C | Laura | Laura |
| D | Paul | Jack |
| E | May | May |
| E | May | May |
+-------------+--------------+-------+
我想分别检查每个项目然后排除
如果项目所有者的名字在col2中,并且其他人与他同在,则删除重复的行Jack Jack
,
a。例如,在Project B中,Jack在Col2中有他的名字,并且他正在与Maria一起工作,因此请删除Jack Jack
b。还要在项目C中删除Laura Laura
如果项目所有者仅自己在项目内部工作,则保留该项目,例如Project A和Project E
如果项目所有者在col2中没有他的名字,则排除项目D,例如项目D
删除重复项,例如Project E
输出表:
+-------------+--------------+-------+
| ProjectName | ProjectOwner | Col2 |
+-------------+--------------+-------+
| A | Sara | Sara |
| B | Jack | Maria |
| C | Laura | May |
| E | May | May |
+-------------+--------------+-------+
我尝试过此here,但结果没有向我显示Project A和E。
请尝试此代码:
select distinct *
from mytable m
where (ProjectOwner!=Col2 or not exists(select 1 from mytable m1 where m1.ProjectName=m.ProjectName and m1.ProjectOwner=m.ProjectOwner and m.Col2!=m1.Col2) )
and ProjectName in (select ProjectName from mytable where ProjectOwner=Col2 )
您可以通过使用GROUPING和COUNT聚合来通过此嵌套SQL获得所需的结果:
select ProjectName, ProjectOwner, Col2
from
(
select ProjectName, ProjectOwner, Col2,
count(1) over ( partition by ProjectName ) cnt
from mytable
group by ProjectName, ProjectOwner, Col2
) q
where ( q.cnt = 1 or ProjectOwner != col2 )
and ProjectOwner in ( select col2 from mytable );
使用EXISTS
和ROW_NUMBER()
功能:
select top (1) with ties *
from table t
where exists (select 1
from table t1
where t1.ProjectName = t.ProjectName and
t1.Col2 = t.ProjectOwner
)
order by dense_rank() over (partition by ProjectName
order by (case when t.ProjectOwner = Col2
then 1 else 0
end)
);