用户向对方消息框发送消息,如何找到知道最多其他用户的用户(接收和发送??)。我有SQL Server。
表:
用户可以发送和接收,因此谁知道其他大多数用户(通过发送和接收?)
答案 0 :(得分:3)
WITH usr_list AS (
SELECT x.user_id,
x.message_from_user AS other_user
FROM TABLE x
UNION
SELECT y.user_id,
y.message_to_user AS other_user
FROM TABLE y)
SELECT TOP 1
ul.user_id,
COUNT(*) AS num_friends
FROM usr_list ul
GROUP BY ul.user_id
ORDER BY num_friends DESC
SELECT TOP 1
ul.user_id,
COUNT(*) AS num_friends
FROM (SELECT x.user_id,
x.message_from_user AS other_user
FROM TABLE x
UNION
SELECT y.user_id,
y.message_to_user AS other_user
FROM TABLE y) ul
GROUP BY ul.user_id
ORDER BY num_friends DESC
答案 1 :(得分:2)
未经测试,但这应该确保每个其他用户只计算一次,无论他们是发件人还是收件人,或者他们发送或接收了多少邮件:
SELECT TOP 1
user_id,
friend_count = COUNT(DISTINCT u)
FROM
(
SELECT user_id,
u = message_from_user
FROM table
UNION ALL
SELECT user_id,
u = message_to_user
FROM table
) AS x
ORDER BY friend_count DESC;