如何根据SQL中的条件过滤出某些行

时间:2018-06-25 12:58:42

标签: sql sql-server ssms

我有此输入表:

+-------------+--------------+-------+
| 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   |
+-------------+--------------+-------+

我想分别检查每个项目然后排除

  1. 如果项目所有者的名字在col2中,并且其他人与他同在,则删除重复的Jack Jack行,

    a。例如,在Project B中,杰克的名字在Col2中,并且他正在与Maria一起工作,因此请删除Jack Jack

    b。还要在项目C中删除Laura Laura

  2. 如果项目所有者仅自己在项目内部工作,则保留该项目,例如Project A和Project E

  3. 如果项目所有者的col2中没有他的名字,则排除项目D之类的项目

  4. 删除重复的项目,例如Project E

输出表:

+-------------+--------------+-------+
| ProjectName | ProjectOwner | Col2  |
+-------------+--------------+-------+
| A           | Sara         | Sara  |
| B           | Jack         | Maria |
| C           | Laura        | May   |
| E           | May          | May   | 
+-------------+--------------+-------+

我尝试了这个here,但结果没有向我显示Project A和E

3 个答案:

答案 0 :(得分:1)

请尝试以下代码:

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 )

Demo

答案 1 :(得分:0)

使用EXISTSROW_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)
                           );

答案 2 :(得分:0)

通过使用 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 );

SQL Fiddle Demo