1

I have table with sample data as follows

-----------------------------
UserID   | ScreenID | rights |
------------------------------
 admin        22         0
 admin        23         0
 admin        24         0

 userA        22         1
 userA        23         1
 userA        24         1

 userB        22         0
 userB        23         0
 userB        24         1

Now I want to fetch 'UserID' and 'rights' details as follows: For each user if the "rights" for all the ScreenIDs are same then that rights value (either '0' or '1') else rights value as 2

That means, required output from the above table should be:

admin , 0
userA , 1
userB  ,2

Please help me in writing SQL query for the same. Thanks.

2 Answers 2

5

With a cte or derived table which does a GROUP BY on UserId, you can then tell whether all Rights are the same:

SELECT UserID,
       CASE 
          WHEN minR = maxR THEN minR
          ELSE 2
       END AS Result
FROM
(
  SELECT UserID, MIN(Rights) as minR, MAX(Rights) as maxR
  FROM UserRights
  GROUP BY UserID
) x;

SqlFiddle here

Sign up to request clarification or add additional context in comments.

Comments

2

Something like (untested on sqlserver):

select userid
     , case when min(rights) = max(rights) 
            then min(rights) 
            else 2 
       end 
from t 
group by userid

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.