Question

Situation: I have a scenario in which I get data with all the fields same except just one field. I have written a store procedure that gets the data, using many join from different table. In my case I need either of the two case depending on the scenario. eg:

Actual case

  |UserId | First name | Last name | IsRequired | IsDeleted |
     1        harry          tom        true         false
     1        harry          tom        false        false
     3         ram            sham       true         false

Scenario:

If there are two records on with IsRequired true and false respectively then I need a case with the IsRequired true.

Problem:

Now the problem is that I need to filter out the records in the select statement.

So any one has any idea how to do it in a select statement.

Expected case:

| UserId | First name | Last name | IsRequired | IsDeleted |
    1        harry          tom        true         false
    2        ram            sham       true         false
Was it helpful?

Solution

UPDATED SOLUTION:

SELECT UserId, First name, Last name, IsRequired, IsDeleted FROM table WHERE UserId IN (SELECT UserId FROM users GROUP BY UserId HAVING count(distinct(IsRequired)) > 1) and IsRequired = 'true'
UNION
SELECT UserId, First name, Last name, IsRequired, IsDeleted FROM table WHERE UserId IN (SELECT UserId FROM users GROUP BY UserId HAVING count(IsRequired) = 1)

Please see http://sqlfiddle.com/#!3/d178f/1/0

Have reproduced the exact same database structure.

OTHER TIPS

Try this: Just It is my idea.

Step 1: First of all change your datatype value of IsRequired into BOOLEAN. So what you have, In IsRequired column contains the value like 0 or 1.

step 2: Then using MAX(). Query is

SELECT userId,firstname,lastname,MAX(IsRequired),IsDeleted FROM `table_name` GROUP BY userId
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top