【发布时间】:2014-09-03 03:10:27
【问题描述】:
我正在开发一个典型的博客应用程序,并有一个返回以下数据的视图:
| post_id | title | publish_on | tag_id | tag_name |
| 1 | Why is Postgres awesome | 2014-09-02 | 1 | tech |
| 1 | Why is Postgres awesome | 2014-09-02 | 2 | postgres |
| 2 | How to ask a question on stackoverflow | 2014-09-10 | 1 | tech |
| 2 | How to ask a question on stackoverflow | 2014-09-10 | 2 | postgres |
| 2 | How to ask a question on stackoverflow | 2014-09-10 | 3 | guide |
| 3 | This is a draft | null | null | null |
| 4 | This is something else without a tag | 2014-10-10 | null | null |
| 5 | This question is also published on 9/2 | 2014-09-02 | null | null |
| 6 | And so is this | 2014-09-02 | 1 | tech |
| 7 | But this one is on 9/10 | 2014-09-10 | 3 | guide|
| 8 | This is on 10/10 | 2014-10-10 | null | null |
| 9 | And so is this | 2014-10-10 | 2 | postgres |
| 10| This is another draft | null | null | null |
我希望按 publish_on 日期对帖子进行分组,然后为每个存储桶选择前 3 个帖子(这将显示在仪表板中,以便用户可以知道今天、下周某个时间以及稍后发布的帖子) 现在我尝试了 these solutions 使用类似的东西:
ROW_NUMBER() OVER (PARTITION BY publish_on ORDER BY publish_on DESC)
但由于有多个标签,行可能会重复,因此这些查询会失败。我还尝试了各种 PARTION BY 标准的组合,但我想我对它们的理解不够好,无法让它发挥作用。
任何帮助/指针表示赞赏!
更新:预期输出
对于每个 publish_on 日期,我希望获得 N (3) 篇预计在该日期发布的帖子。
| 1 | Why is Postgres awesome | 2014-09-02 | 1 | tech |
| 1 | Why is Postgres awesome | 2014-09-02 | 2 | postgres |
| 5 | This question is also published on 9/2 | 2014-09-02 | null | null |
| 6 | And so is this | 2014-09-02 | 1 | tech |
| 2 | How to ask a question on stackoverflow | 2014-09-10 | 1 | tech |
| 2 | How to ask a question on stackoverflow | 2014-09-10 | 2 | postgres |
| 2 | How to ask a question on stackoverflow | 2014-09-10 | 3 | guide |
| 7 | But this one is on 9/10 | 2014-09-10 | 3 | guide|
| 4 | This is something else without a tag | 2014-10-10 | null | null |
| 8 | This is on 10/10 | 2014-10-10 | null | null |
| 9 | And so is this | 2014-10-10 | 2 | postgres |
| 3 | This is a draft | null | null | null |
| 10| This is another draft | null | null | null |
希望这能让问题更清楚易懂。
【问题讨论】:
-
tag_id 和 tag_name 是否相关?我假设是这样,但 tag_id 有相关的 tag_name 'postgres' 和 'guide'。
-
@simo.3792095 抱歉,它们是相关的。将更新表格以反映这一点。谢谢!
-
我假设 post_id 的 4、8 和 10 将在 10 月 10 日分组显示。您目前在 9 月 10 日之前显示 post_id 4。
-
啊,你说得对,4、8、9应该分开分组!
-
是的 4,8 & 9 - 不是我说的 4, 8 & 10。 ;-0
标签: sql postgresql