Search code examples
sql-servercountsubquerymaxwith-statement

Choose row that equal to the max value from a query


I want to know who has the most friends from the app I own(transactions), which means it can be either he got paid, or paid himself to many other users.

I can't make the query to show me only those who have the max friends number (it can be 1 or many, and it can be changed so I can't use limit).

;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

I just can't figure it out, I've tried count, max(count), where = max, nothing worked.

It's a two columns table - "Member_No" and "Paid" - member pays the money, and the paid is the one who got the money.

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
  • It's from Excel, but I loaded it into sql-server.
  • It's just a sample, there are 1000 more rows

Solution

  • It seems like you are massively over-complicating this. There is no need for self-joining.

    Just unpivot each row so you have both sides of the relationship, then group it up by one side and count distinct of the other side

    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