如何连接两表并按年月分组统计当月唯一作者数量?
统计每月发布内容的唯一作者数量
数据表结构
serialized_book表
id | author | title ---+--------+--------------------------- 0 | foo | i am foo. 1 | bar | the derivabloviating . . . ...
chapter_pub_date表
id | chapter | year | month | day | book_id ---+---------+------+-------+-----+--------- 0 | 1 | 2024 | 12 | 10 | 0 1 | 2 | 2025 | 1 | 5 | 0 ... 27 | 1 | 2024 | 12 | 10 | 1 ...
需求
需要编写SQL查询,得到每月发布内容的唯一作者数量,期望结果如下:
month | unique_author_count --------+-------------------- 2024-12 | 2 2025-1 | 1 ...
现有代码的问题
你当前的SQL语句只得到了「作者+发布年月」的唯一组合,但没有进一步按年月统计作者数量:
select w.author, concat(p.year, "-", p.month) as yr_mo from serialized_book w join chapter_pub_date p on w.id = p.book_id group by w.author, yr_mo order by yr_mo desc
解决方案
不需要用窗口函数(partition),两种简单写法就能实现需求:
写法1:子查询去重后统计
先通过子查询得到每个作者在每个月的唯一记录,再按年月分组计数:
select yr_mo as month, count(author) as unique_author_count from ( select w.author, concat(p.year, '-', lpad(p.month, 2, '0')) as yr_mo from serialized_book w join chapter_pub_date p on w.id = p.book_id group by w.author, yr_mo ) as author_month_groups group by yr_mo order by yr_mo;
写法2:直接在主查询中去重统计
更简洁的方式,直接在主查询里对作者去重,同时按年月分组:
select concat(p.year, '-', lpad(p.month, 2, '0')) as month, count(distinct w.author) as unique_author_count from serialized_book w join chapter_pub_date p on w.id = p.book_id group by month order by month;
关键说明
lpad(p.month, 2, '0')是为了让月份格式统一(比如1月显示为01),确保2025-1变成2025-01,排序和显示更规范;如果不需要补零,直接用concat(p.year, '-', p.month)即可。count(distinct w.author)是核心:它会自动忽略同一月份内的重复作者,直接统计该月的唯一作者数量。
内容的提问来源于stack exchange,提问作者user1713450
相关产品推荐
相关产品推荐

