4

I have this Input Table:

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

I want to check each project separately then exclude

  1. If the project owner has his name inside col2 and other people with him, then remove the row which is repetitive Jack Jack,

    a. For example, In Project B Jack has his name inside Col2 and he is working with Maria , so remove Jack Jack

    b. Also remove Laura Laura in Project C

  2. If Project owner only himself working inside the project then keep it, like Project A and Project E

  3. If Project owner doesn't have his name inside col2 then exclude the project like Project D

  4. Remove duplicate like Project E

Output Table:

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

I tried this here but the results didn't show me Project A and E.

Dale K
  • 25,246
  • 15
  • 42
  • 71
sara
  • 534
  • 1
  • 9
  • 22

3 Answers3

1

Please try this code:

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

Hamed Naeemaei
  • 8,052
  • 3
  • 37
  • 46
0

Use EXISTS WITH ROW_NUMBER() function :

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)
                           );
Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52
0

You may get the desired results by this nested SQL by using GROUPING and COUNT agggregation :

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

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55