TSQL - 如果每个组中至少有1个用户有效,那么将该组返回为有效?

时间:2017-05-30 17:13:44

标签: sql tsql group-by row

基本上我想运行一个返回所有DISTINCT组列表的查询,如果每个组中至少有一个用户的Valid为true,则返回该组为true。否则将该组返回为false。非常感谢

这是我的表:

UserID | GroupID | Valid
------------------------
1         1        True
2         2        False
3         3        False
4         1        False
5         4        True

预期结果

UserID | GroupID | Valid
------------------------
1         1        True
2         2        False
3         3        False
5         4        True

3 个答案:

答案 0 :(得分:2)

您可以使用row_number()

select t.*
from (select t.*,
             row_number() over (partition by groupid
                                order by (case when valid = 'True' then 1 else 2 end)
                               ) as seqnum
      from t
     ) t
where seqnum = 1;

答案 1 :(得分:1)

您可以执行此countmin窗口功能。 (假设您的SQL Server版本支持它们)

select first_user as userid,groupid,new_valid as valid
from (
select t.*
,min(userID) over(partition by groupid) as first_user
,case when count(case when valid='True' then 1 end) over(partition by groupid) > 0 then 'True' else 'False' end as new_valid
from tbl t
) t
where first_user=userID

如果每个groupID需要 first true或false userID,请使用

select first_user as userid,groupid,new_valid as valid
from (
select t.*
,case when count(case when valid='True' then 1 end) over(partition by groupid) > 0 then min(case when valid='True' then userID end) over(partition by groupid)
 else min(userID) over(partition by groupid) end as first_user
,case when count(case when valid='True' then 1 end) over(partition by groupid) > 0 then 'True' else 'False' end as new_valid
from tbl t
) t
where first_user=userID 

答案 2 :(得分:0)

你可以这样做:

SELECT      MAX(UserID),
            GroupID,
            Valid 
FROM        yourtable
WHERE       Valid = 1 
OR          (Valid = 0 and GroupID not in (SELECT GroupID FROM yourtable WHERE Valid = 1))
Group By    GroupID, Valid
order by    MAX(UserID)

这样您将获得一个组的最后一个UserID。如果想要第一个,只需将MAX更改为MIN。