我有一个跟踪粉丝的表
FollowerUserId, FollowingUserId
1 2
2 1
3 1
4 1
1 5
我想让所有给定Id的用户跟随,然后是或者两者。 例如对于UserId 1,我希望结果为:(FG:关注,FD:关注,B:两种方式)
2,B
5,FG
3,FD
4,FD
我可以通过联盟轻松获得FG和FD
Select FollowerUserId, 'FD' From Table Where FollowingUserId =1
Union
Select FollowingUserId, 'FG' From Table Where FollowerUserId =1;
以上我将用户2作为
2,FG
2,FD
从上面但我真的需要2,B 没有UserId 2重复。 如何有效地完成这项工作?
答案 0 :(得分:1)
您可以在基本查询中使用聚合:
SELECT UserId,
(CASE WHEN COUNT(DISTINCT which) = 1 THEN MIN(which)
ELSE 'B'
END)
FROM (Select FollowerUserId as UserId, 'FD' as which From Table Where FollowingUserId = 1
Union ALL
Select FollowingUserId, 'FG' From Table Where FollowerUserId = 1
) f
GROUP BY UserId;