# 每个标签的主题数量

**URL:** https://meta.discourse.org/t/number-of-topics-per-tag/139957
**Category:** Data & reporting
**Tags:** sql-query
**Created:** [2020 年1 月 28 日 16:26 UTC](https://meta.discourse.org/t/number-of-topics-per-tag/139957 "2020-01-28T16:26:29Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![tpetrov](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/tpetrov/32/164643_2.png) [@tpetrov](https://meta.discourse.org/u/tpetrov)
#### Post date: [2020 年1 月 28 日 16:26 UTC](https://meta.discourse.org/t/number-of-topics-per-tag/139957/1 "2020-01-28T16:26:29Z")

</div>

我希望能够获取所有标签的列表，以及每个标签在特定时间段（例如上个月）内创建的新主题/帖子数量。  
有人能帮忙提供查询方法吗？

---

<div class="post-metadata">

### Author: ![Mittineague](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/mittineague/32/114259_2.png) [@Mittineague](https://meta.discourse.org/u/Mittineague)
#### Post date: [2020 年1 月 28 日 21:07 UTC](https://meta.discourse.org/t/number-of-topics-per-tag/139957/2 "2020-01-28T21:07:42Z")

</div>

我想你可以逐行查阅文件，但依我看，使用插件管理页面上的菜单会更高效。你应该能看到许多表格，选中它们后便会显示字段名称和架构信息。

我现在不在电脑前，但该模型包含以下内容：

```plaintext
# == 架构信息
#
# 表名：topic_tags
#
# id :integer 不为空，主键
# topic_id :integer 不为空
# tag_id :integer 不为空
# created_at :datetime 不为空
# updated_at :datetime 不为空
#
# 索引
#
# index_topic_tags_on_topic_id_and_tag_id (topic_id,tag_id) 唯一

```

注意其中的“`topic_id`”和“`tag_id`”，这表明命名规则为“表名\_下划线\_字段名”。

`tags` 表包含：

```plaintext
# == 架构信息
#
# 表名：tags
#
# id :integer 不为空，主键
# name :string 不为空
# topic_count :integer 默认值(0)，不为空
# created_at :datetime 不为空
# updated_at :datetime 不为空
# pm_topic_count :integer 默认值(0)，不为空
# target_tag_id :integer
#
# 索引
#
# index_tags_on_lower_name (lower((name)::text)) 唯一
# index_tags_on_name (name) 唯一

```

至于 `topic` 表的字段，就留给你自行查看了。

不过，这可能有点操之过急了。你之前是否尝试过对这些表中的某一个运行一个非常简单的查询，作为“数据探索器你好”的测试？具体是什么查询呢？

---

<div class="post-metadata">

### Author: ![tpetrov](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/tpetrov/32/164643_2.png) [@tpetrov](https://meta.discourse.org/u/tpetrov)
#### Post date: [2020 年1 月 29 日 14:28 UTC](https://meta.discourse.org/t/number-of-topics-per-tag/139957/3 "2020-01-29T14:28:55Z")

</div>

太棒了，非常感谢这些提示。  
我成功构建了它。可能还不够完美，但如果对其他人有用：

**每个标签的新主题数量**

```
-- [params]
-- int :months_ago = 0

WITH query_period as (
    SELECT
        date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' as period_start,
        date_trunc('month', CURRENT_DATE) - INTERVAL ':months_ago months' + INTERVAL '1 month' - INTERVAL '1 second' as period_end
)
SELECT
    tags.name,
    count(1) as topic_count
FROM topics t
RIGHT JOIN topic_tags tt
    ON t.id = tt.topic_id
RIGHT JOIN tags tags
    ON tt.tag_id = tags.id
RIGHT JOIN query_period qp
    ON t.created_at >= qp.period_start
        AND t.created_at <= qp.period_end
WHERE t.user_id > 0
    AND tt.topic_id IS NOT NULL
GROUP BY tags.name
ORDER BY topic_count DESC

```
