ts_vector按月分组

时间:2018-10-22 07:59:16

标签: sql postgresql tsvector

给出以下SQL

SELECT 'food' keyword, sum(ndoc) documents, sum(nentry) occurances
FROM ts_stat('SELECT tsvector FROM posts WHERE created_at BETWEEN ''2018-06-01'' AND ''2018-10-01''')
WHERE word IN ('food');

我想按月对结果进行分组,以便最终结果包含3列,其中第一列为月份,第二和第三列为ndoc和nentry。

我尝试使用以下SQL,但没有运气:

SELECT created_at, "food" keyword, sum(ndoc) documents, sum(nentry) occurances
FROM ts_stat('SELECT tsvector, created_at FROM posts WHERE created_at BETWEEN ''2018-06-01'' AND ''2018-10-01''')
WHERE word IN ('makanan')
GROUP BY MONTH(created_at);

有人可以帮助我吗?

编辑

这是我的DDL

create table posts
(
    id serial not null
        constraint posts_pkey
            primary key,
    . 
    . . 
    . . .
    . . 
    . 
    created_at timestamp,
    updated_at timestamp,
    location geography(Point,4326),
    tsvector tsvector
)
;

create index index_posts_on_city_id_and_category_id
    on posts (city_id, category_id)
;

create index index_posts_on_city_id_and_district_id
    on posts (city_id, district_id)
;

create index index_posts_on_city_id
    on posts (city_id)
;

create index index_posts_on_category_id
    on posts (category_id)
;

create index index_posts_on_district_id_and_category_id
    on posts (district_id, category_id)
;

create index index_posts_on_subcategory_id
    on posts (subcategory_id)
;

create index index_posts_on_location
    on posts (location)
;

create index index_posts_on_tsvector
    on posts (tsvector)
;

2 个答案:

答案 0 :(得分:0)

尝试使用EXTRACT(MONTH FROM created_at)

 SELECT EXTRACT(MONTH FROM created_at) AS mon,
       'food' AS keyword,
        sum(ndoc) documents,
        sum(nentry) occurances
FROM ts_stat('SELECT tsvector, created_at FROM posts WHERE created_at BETWEEN ''2018-06-01'' AND ''2018-10-01''')
WHERE word IN ('makanan')
GROUP BY EXTRACT(MONTH FROM created_at);

答案 1 :(得分:0)

这是您想要的吗?

SELECT 
    to_char(created_at, 'MM') as Month, 
    'food' keyword,
    sum(ndoc) documents, 
    sum(nentry) occurances
FROM 
    ts_stat('SELECT tsvector, created_at FROM posts WHERE created_at BETWEEN ''2018-06-01'' AND ''2018-10-01''')
WHERE 
    word IN ('makanan')
GROUP BY 
    to_char(created_at, 'MM');