找到联系人最多的用户

时间:2010-01-24 20:12:32

标签: sql sql-server tsql

用户向对方消息框发送消息,如何找到知道最多其他用户的用户(接收和发送??)。我有SQL Server。

表:

  • USER_ID
  • USER_NAME
  • USER_GROUP
  • MESSAGE_ID
  • MESSAGE_MESSAGE
  • MESSAGE_FROM_USER
  • M_ESSAGE_TO_USER

用户可以发送和接收,因此谁知道其他大多数用户(通过发送和接收?)

2 个答案:

答案 0 :(得分:3)

SQL Server 2005+,使用CTE:


 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

非CTE当量:


  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;