如何解决从 reg_ex_split_table 输出中去除空白结果
我有一个查询,它计算一列中的所有单词,并给出单词的频率和频率排名作为结果。出于某种原因,我不断收到一个没有字的行。我该如何摆脱它?
表格:
master = [[{"activity":"tx"},{"activity":"fl","ids":'123'},{"activity":"ia"}],[{"activity":"tx"},"ids":'456'},"ids":'789'},"ids":'432'},{"activity":"ia"}]]
插入:
CREATE TABLE dummy (
created_at TIMESTAMPTZ,tweet TEXT);
查询:
INSERT INTO dummy VALUES ('2020-12-18 00:00:00+00','foo squared');
INSERT INTO dummy VALUES ('2020-12-18 00:00:00+00','foo foo');
INSERT INTO dummy VALUES ('2020-12-18 00:00:00+00','foo bar');
返回:
select *
from (
select date_trunc('day',created_at) as created_day,word,count(*) as cnt,rank() over(partition by date_trunc('day',created_at) order by count(*) desc) rn
from dummy d
cross join lateral regexp_split_to_table(
regexp_replace(tweet,'\y(rt|co|https|bar|none)\y','','g'),'\s+'
) w(word)
group by created_day,word
) d
where created_day = CURRENT_DATE and word IS NOT NULL
order by rn
LIMIT 10;
我想去掉空白词:
created_day | word | cnt | rn
------------------------+---------+-----+----
2020-12-18 00:00:00+00 | foo | 4 | 1
2020-12-18 00:00:00+00 | | 2 | 2
2020-12-18 00:00:00+00 | arm | 1 | 3
2020-12-18 00:00:00+00 | squared | 1 | 3
解决方法
问题出在内部 regexp_replace()
;当匹配部分位于字符串末尾时,字符串末尾会有一个尾随空格。基本上,当应用于 'foo bar'
时,它会生成 'foo '
。
然后在解析时生成一个最终单词,其值为空字符串 (''
)。
一个简单的解决方法是trim()
regexp_replace()
的输出,所以基本上替换:
cross join lateral regexp_split_to_table(
regexp_replace(tweet,'\y(rt|co|https|bar|none)\y','','g'),'\s+'
) w(word)
与:
cross join lateral regexp_split_to_table(
trim(regexp_replace(tweet,'g')),'\s+'
) w(word)
,
你能在where
子句中使用它吗?
where created_day = CURRENT_DATE
And word is not null -- this
order by rn;
或者你也可以在这里使用相同的条件。
) w(word)
word is not null -- this
group by created_day,word
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。