SQL:按周

时间:2017-05-19 15:11:29

标签: sql postgresql

我编写了一个如下所示的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,但是乞丐不能成为选择者。

1 个答案:

答案 0 :(得分:3)

使用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)