Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

54 浏览文章 Ⅱ #66

Open
astak16 opened this issue Mar 25, 2022 · 0 comments
Open

54 浏览文章 Ⅱ #66

astak16 opened this issue Mar 25, 2022 · 0 comments
Labels

Comments

@astak16
Copy link
Owner

astak16 commented Mar 25, 2022

题目

题目链接:浏览文章 Ⅱ

此表的每一行都表示某人在某天浏览了某位作者的某篇文章。

请注意,同一人的 author_idviewer_id 是相同的。

编写一条 SQL 查询同一天阅读至少两篇文章的人,结果按照 author_id 升序排列。

create table views (
  article_id int, 
  author_id int, 
  viewer_id int,
  view_date date
);

insert into views (article_id, author_id, viewer_id, view_date) values 
(1, 3, 5, '2019-08-01'),
(3, 4, 5, '2019-08-01'),
(1, 3, 6, '2019-08-02'),
(2, 7, 7, '2019-08-01'),
(2, 7, 6, '2019-08-02'),
(4, 7, 1, '2019-07-22'),
(3, 4, 4, '2019-07-21'),
(3, 4, 4, '2019-07-21');

SQL:

select
  distinct viewer_id id
from views group by view_date, viewer_id
having count(distinct article_id) >= 2 order by id;

解析

  • 按照 view_dateviewer_id 分组,并使用 having 筛选
    • 如果是 having count(viewer_id) >= 2 将会筛选出查看同一篇文章的人
    • 所以使用 having count(distinct article_id) >= 2 就能筛选出一个人一天至少查看了两篇文章
  • 使用 distinctviewer_id 进行去重
    • 因为可能会有一个人在不同的时间都看了两篇以上的文章
@astak16 astak16 added the 中等 label Mar 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant