簡體   English   中英

SQL查詢MAX值屬性1和帶有雙項過濾器的獨特服裝2

[英]SQL Query MAX value attribute 1 and distinct attibute 2 with filter of double entries

我希望有人可以幫助我的SQL查詢。

我有一張看起來像這樣的桌子:

ID | post_id | 喜歡| 一些東西...

1 | 1000 | 5 | ...

2 | 1000 | 20 | ...

3 | 1001 | 7 | ...

4 | 1002 | 11 | ...

5 | 1003 | 19 | ...

6 | 1003 | 19 | ...

7 | 1003 | 18 | ...

8 | 1004 | 17 | ...

9 | 1005 | 6 | ...

現在,我需要將它們過濾為MAX個贊和不同的帖子ID。

我找到了此代碼,但在我的情況下無法正常工作100%。 它給了我最大的喜好並區分了帖子ID,但只有一次與最大的ID不同。 如果存在3次相同的條目,則不會有區別。 我需要過濾掉兩次。 希望有人可以在這里提供幫助。

 SELECT p.*
    FROM posts p
    INNER JOIN
        (SELECT post_id, MAX(likes) AS MaxLikes
        FROM posts
        GROUP BY post_id) grouped 
    ON p.post_id = grouped.post_id 
    AND p.likes = grouped.MaxLikes
    ORDER BY p.post_id ASC

結果如下:

ID | post_id | 喜歡| 一些東西...

2 | 1000 | 20 | ...

3 | 1001 | 7 | ...

4 | 1002 | 11 | ...

5 | 1003 | 19 | ...

6 | 1003 | 19 | ...

8 | 1004 | 17 | ...

9 | 1005 | 6 | ...

您需要使用相關方法的subquery

select p.*
from posts p
where p.likes = (select max(p1.likes) from posts p1 where p1.post_id = p.post_id);

如果您使用的是MySql 8+,則可以嘗試以下操作:

Select * from
(Select *, Row_Number() over (partition by post_id order by likes desc) as ranking)c
where ranking = 1

嘗試這個

Select max(id) as id, post_id, likes
From posts
Where (post_id, likes) in (Select  post_id, max(likes) from posts group by post_id)
group by post_id, likes

暫無
暫無

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

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