我想知道在这样的数据库设置中获取每个用户的所有活动连接数的最佳方法是什么。在查询中只应使用前两个组。结果集是我希望查询的输出看起来像。
要记住的一件事是,用户记录可能已被删除但未反映在Connections表中。结果集应仅计算与仍在users表中的其他帐户的连接。我还想按伯爵对结果进行排序。
答案 0 :(得分:1)
SELECT Users.UserId,count(*) Count
FROM ConnectionsTable
JOIN Users ON ( Users.UserId = Requestor OR Users.UserId = Requestee)
GROUP BY Users.UserId
ORDER BY count(*) DESC
答案 1 :(得分:0)
SELECT source.UserId, COUNT(*) as [Count]
FROM
(
(
SELECT Requestor as UserID
FROM Connections
)
UNION ALL
(
SELECT Requestee as UserID
FROM Connections
)
) source
WHERE Exists (SELECT top 1 1 FROM Users us WHERE us.UserId = source.UserId)
GROUP BY source.UserId