我有2个表,其中包含相同的列和权限记录。 两个表中都有一列名为IsAllow的列。 我使用UNION获取两个表的记录 但是如果在任何一列中IsAllow = 0,我想跳过类似的记录 - 我不想要那些记录。但UNION会返回所有记录并且感到困惑。
Below are columns
IsAllow, UserId, FunctionActionId
我尝试了联盟,但它给出了两个记录。我想在两个表中排除IsAllow = 0.
Sample data table 1
IsAllow UserId FunctionActionId
1 2 5
1 2 8
Sample data table 2
IsAllow UserId FunctionActionId
0 2 5 (should be excluded)
1 2 15
答案 0 :(得分:1)
你可以试试这个:
;with cte as(select *, row_number()
over(partition by UserId, FunctionActionId order by IsAllow desc) rn
from
(select * from table1
union all
select * from table2) t)
select * from cte where rn = 1 and IsAllow = 1
版本2:
select distinct coalesce(t1.UserId, t2.UserId) as UserId,
coalesce(t1.FunctionActionId, t2.FunctionActionId) as FunctionActionId,
1 as IsAllow
from tabl1 t1
full join table2 t2 on t1.UserId = t2.UserId and
t1.FunctionActionId = t2.FunctionActionId
where (t1.IsAllow = 1 and t2.IsAllow = 1) or
(t1.IsAllow = 1 and t2.IsAllow is null) or
(t1.IsAllow is null and t2.IsAllow = 1)