postgresql SQL:拆分字符串并按周计算出现次数

kuuvgm7e  于 2024-01-07  发布在  PostgreSQL
关注(0)|答案(1)|浏览(140)

我写了一个SQL查询,看起来像这样:

SELECT date_trunc('week', created_at)::date AS week, posted_to AS providers
FROM documents
GROUP BY week, providers
ORDER BY week, providers

字符串
一个典型的行输出看起来像这样:

2017-05-08  {facebook_2214,facebook_2215,facebook_2216,twitter_2219}


我想计算单词facebooktwitterlinkedin或其他单词每周出现的次数,所以按facebook分组本周应该返回3twitter本周应该返回1。列类型是数组。
有什么想法吗?我宁愿它是抽象的,而不是为每个可能的结果写一个AS facebook,但乞丐不能挑肥拣瘦。

ilmyapht

ilmyapht1#

使用split_part()提取提供程序名称,并按日期、提供程序分组计算总和:

with my_data(date, providers) as (
values
    ('2017-05-08', '{facebook_2214,facebook_2215,facebook_2216,twitter_2219}'::text[]),
    ('2017-05-15', '{twitter_2220,twitter_2221,linkedin_2222}')
)

select date, provider, count(*)
from (
    select date, split_part(u, '_', 1) as provider
    from my_data,
    unnest(providers) u
    ) s
group by 1, 2
order by 1, 2;

    date    | provider | count 
------------+----------+-------
 2017-05-08 | facebook |     3
 2017-05-08 | twitter  |     1
 2017-05-15 | linkedin |     1
 2017-05-15 | twitter  |     2
(4 rows)

字符串

相关问题