用于根据多个行值获取输出的SQL查询

时间:2014-06-06 04:36:42

标签: sql sql-server

我的表格包含如下样本数据

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

现在我想获取'UserID'和'rights'详细信息,如下所示:      对于每个用户   如果所有ScreenID的“权限”与该权利值(“0”或“1”)相同   其他权利值为2

这意味着,上表所需的输出应为:

admin , 0
userA , 1
userB  ,2

请帮我写一下SQL查询。感谢。

2 个答案:

答案 0 :(得分:5)

使用cte或派生表在GROUP BY上执行UserId,您可以判断所有Rights是否相同:

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

答案 1 :(得分:2)

类似(在sqlserver上未经测试):

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