sql query question

deepika omer 1 Reputation point
2021-05-21T10:09:46.323+00:00

Can someone pls tell me how to get below output using subquery

![98459-q1.png]1

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,657 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Erland Sommarskog 112.7K Reputation points MVP
    2021-05-21T22:08:18.357+00:00
    SELECT Emp, Salary, reverse, type
    FROM   tbl
    WHERE  NOT (Emp = 1 AND revers = 1)
    

    Or is there any particular business logic involved?

    0 comments No comments

  2. MelissaMa-MSFT 24,201 Reputation points
    2021-05-24T03:05:12.203+00:00

    Hi @deepika omer ,

    Welcome to Microsoft Q&A!

    For this type of problem we recommend that you post CREATE TABLE statements for your tables together with INSERT statements with sample data, enough to illustrate all angles of the problem. We also need to see the expected result of the sample.

    Furthermore, it helps to have a short description of the business rules whih explains why you want that result.

    Suppose you would like to filter out all the rows like below:

    1. if one emp has both 1 and 0 as revers, then choose all rows where revers=0
    2. if one emp has only one revers either 0 or 1, remain it.

    Please refer below and check whether it is helpful.

    create table tablede  
    (Emp int,  
    salary int,  
    revers bit,  
    type int)  
      
    insert into tablede values  
    (101,1000,0,40),  
    (101,1000,1,40),  
    (101,1000,0,40),  
    (102,2000,1,40),  
    (103,3000,0,40)  
    
    select  a.*   
    from tablede a   
    inner join   
    (select emp, count(revers) count from tablede group by emp) b   
    on a.Emp=b.Emp  
    where count=1 or (count>1 and revers=0)  
    

    Output:

    Emp	salary	revers	type  
    101	1000	0	40  
    101	1000	0	40  
    102	2000	1	40  
    103	3000	0	40  
    

    Best regards,
    Melissa


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.