我需要编写一个SQL查询,该查询为每个用户生成最流行的故事的名称(根据总阅读次数)。以下是一些示例数据:
story_name | user | age | reading_counts -----------|-------|-----|--------------- story 1 | user1 | 4 | 12 story 2 | user2 | 6 | 14 story 4 | user1 | 4 | 15
这是我到目前为止的内容,但我认为这是不正确的:
Select *
From mytable
where (story_name,reading_counts)
IN (Select id, Max(reading_counts)
FROM mytable
Group BY user
)
答案 0 :(得分:3)
reading_counts
(Group By
与Max()
)user
和reading_counts
上的主表,即可获得与用户最大reading_counts
相对应的行。尝试以下查询:
SELECT
t1.*
FROM mytable AS t1
JOIN
(
SELECT t2.user,
MAX(t2.reading_counts) AS max_count
FROM mytable AS t2
GROUP BY t2.user
) AS dt
ON dt.user = t1.user AND
dt.max_count = t1.reading_counts
答案 1 :(得分:0)
SELECT *
FROM mytable
WHERE user IN
(SELECT user, max(reading_counts)
FROM mytable
GROUP BY user)