mysql - SQL编写自定义查询
问题描述
我需要编写一个 SQL 查询,它为每个用户生成最受欢迎的故事的名称(根据总阅读次数)。以下是一些示例数据:
故事名称 | 用户 | 年龄 | 阅读计数 -----------|-------|-----|--------------- 故事1 | 用户1 | 4 | 12 故事2 | 用户2 | 6 | 14 故事4 | 用户1 | 4 | 15
这是我到目前为止所拥有的,但我认为它不正确:
Select *
From mytable
where (story_name,reading_counts)
IN (Select id, Max(reading_counts)
FROM mytable
Group BY user
)
解决方案
- 在派生表中,您可以首先确定每个用户的最大值
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
推荐阅读
- r - 如何使 ggmap 填满 R Shiny 应用程序的整个页面?
- javascript - 获取对象数组中的特定元素
- active-directory - AD 单值自定义属性在 powershell 中返回为多值
- c# - 数组的 GCHandle.AddrOfPinnedObject 是否总是返回指向数组第一个元素的指针?
- r - 将顶点标签放置在圆形图的外部,用于不同大小的顶点和不同大小的标签
- java - 从java中给定的一组数字中查找最大日期和时间
- java - 如何通过透明窗口从屏幕读取数据
- swift - UserDefault.standard 首选项仅正确保存约 80% 的时间
- mysql - 根据 col2 的分组值捕获 col1 的值
- c++ - 将基类指针转换为派生类指针