答案 0 :(得分:1)
你可以试试这个:
SELECT CASE WHEN t.user_id1 > t.userid2 THEN t.user_id1 ELSE t.user_id2 end as user_1,
CASE WHEN t.user_id1 > t.userid2 THEN t.user_id2 ELSE t.user_id1 end as user_2,
COUNT(*) as cnt
FROM YourTable t
GROUP BY CASE WHEN t.user_id1 > t.userid2 THEN t.user_id1 ELSE t.user_id2 end ,
CASE WHEN t.user_id1 > t.userid2 THEN t.user_id2 ELSE t.user_id1 end
结果将如下所示:
user_id1 , user_id2 , count
17 1 1
18 1 3
19 1 1
20 1 3
现在你所要做的就是选择你想要的东西,在这种情况下user_id1 , count from ( .. ) where user_id2 = 1
编辑:对于ID为2的用户,请使用:
SELECT CASE WHEN t.user1id > t.user2id THEN t.user1id ELSE t.user2id end as user_1,
CASE WHEN t.user1id > t.user2id THEN t.user2id ELSE t.user1id end as user_2,
COUNT(*) as cnt
FROM YourTable t
WHERE 2 IN(t.user1id,t.user2id)
GROUP BY CASE WHEN t.user1id > t.user2id THEN t.user1id ELSE t.user2id end ,
CASE WHEN t.user1id > t.user2id THEN t.user2id ELSE t.user1id end