从查询中选择等于最大值的行

Choose row that equal to the max value from a query

我想知道谁在我拥有的应用程序中拥有最多的朋友(交易),这意味着他可以得到报酬,也可以自己支付给许多其他用户。

我无法进行查询以显示 拥有最大好友数的人(可以是 1 个或多个,并且可以更改,所以我可以' t 使用限制)。

;with relationships as 
(
    select
      paid as 'auser',
      Member_No as 'afriend'
    from Payments$
    union all
    select
      member_no as 'auser',
      paid as 'afriend'
    from Payments$
),
DistinctRelationships AS (
    SELECT DISTINCT *
    FROM relationships
)
select
  afriend,
  count(*) cnt
from DistinctRelationShips
GROUP BY
  afriend
order by
  count(*) desc

我就是想不通,我试过 count, max(count), where = max, 什么都没用。

这是一个两列table - “Member_No”和“付费” - 会员支付了钱,付费的就是得到钱的人。

Member_No Paid
14 18
17 1
12 20
12 11
20 8
6 3
2 4
9 20
8 10
5 20
14 16
5 2
12 1
14 10

看来你很over-complicating这个。不需要 self-joining.

只需逆轴旋转每一行,这样您就拥有了关系的两边,然后将它按一边分组并计算另一边的不同

SELECT
-- for just the first then SELECT TOP (1)
-- for all that tie for the top place use SELECT TOP (1) WITH TIES
  v.Id,
  Relationships = COUNT(DISTINCT v.Other),
  TotalTransactions = COUNT(*)
FROM Payments$ p
CROSS APPLY (VALUES
    (p.Member_No, p.Paid),
    (p.Paid, p.Member_No)
) v(Id, Other)
GROUP BY
  v.Id
ORDER BY
  COUNT(DISTINCT v.Other) DESC;

db<>fiddle