簡體   English   中英

從子表獲得最大值的SQL查詢

[英]SQL Query With Max Value from Child Table

三個相關的表:曲目(音樂曲目),用戶和關注者。

下表是將用戶(追隨者)與用戶(追隨者)相關的多對多關系。

我正在尋找最終結果: <track_id><user_id><most popular followee>

前兩列很簡單,是由曲目和用戶之間的關系導致的。 第三是我的問題。 我可以與follows表一起加入,並獲得每個用戶關注的所有關注者,但是如何獲取關注者數量最多的最多關注者。

以下是帶有相關列的表:

tracks: id, user_id (fk to users.id), song_title
users: id
follows: followee_id (fk to users.id), follower_id (fk to users.id)

以下是一些示例數據:

TRACKS
1, 1, Some song title

USERS
1
2
3
4

FOLLOWS
2, 1
3, 1
4, 1 
3, 4
4, 2
4, 3

DESIRED RESULT
1, 1, 4

對於期望的結果,第3字段是4,因為正如您在FOLLOWS表中所看到的那樣,用戶4的關注者數量最多。

我和周圍一些偉大的思想仍在撓頭。

所以我把它扔進了Linqpad,因為我對Linq更好。

Tracks
    .Where(t => t.TrackId == 1)
    .Select(t => new { 
        TrackId = t.TrackId,
        UserId = t.UserId, 
        MostPopularFolloweeId = Followers
            .GroupBy(f => f.FolloweeId)
            .OrderByDescending(g => g.Count())
            .FirstOrDefault()
            .Key
    });

產生的SQL查詢如下(@ p0是軌道ID):

-- Region Parameters
DECLARE @p0 Int = 1
-- EndRegion
SELECT [t0].[TrackId], [t0].[UserId], (
    SELECT [t3].[FolloweeId]
    FROM (
        SELECT TOP (1) [t2].[FolloweeId]
        FROM (
            SELECT COUNT(*) AS [value], [t1].[FolloweeId]
            FROM [Followers] AS [t1]
            GROUP BY [t1].[FolloweeId]
            ) AS [t2]
        ORDER BY [t2].[value] DESC
        ) AS [t3]
    ) AS [MostPopularFolloweeId]
FROM [Tracks] AS [t0]
WHERE [t0].[TrackId] = @p0

這將輸出預期的響應,並且應該是更清晰查詢的開始。

這聽起來像是使用row_number()進行的聚合查詢。 我對所有聯接如何組合在一起感到有些困惑:

select t.*
from (select t.id, f.followee_id, count(*) as cnt,
             row_number() over (partition by t.id order by count(*) desc) as seqnum
      from followers f join
           tracks t 
           on f.follow_id = t.user_id
      group by t.id, f.followee_id
     ) t
where seqnum = 1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM