sql - 从 reg_ex_split_table 输出中删除空白结果
问题描述
我有一个查询,它计算一列中的所有单词,并给我单词的频率和频率等级作为结果。出于某种原因,我不断得到一个没有字的行。我该如何摆脱它?
桌子:
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 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
我想摆脱空白词:
created_day | word | cnt | rn
------------------------+---------+-----+----
2020-12-18 00:00:00+00 | foo | 4 | 1
2020-12-18 00:00:00+00 | arm | 1 | 2
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, '\y(rt|co|https|bar|none)\y', '', 'g')),
'\s+'
) w(word)
推荐阅读
- ruby - Ruby:在脚本运行之间存储和更新变量
- c# - 从什么时候开始 C# 枚举可以是私有的?
- django - 如何处理可变数量传入的连接?
- python - Python:BeautifulSoup 无法解析 html 页面
- openxml-sdk - OpenXml SDK-如何唯一标识word文档中的段落
- docker - 使用 Kubernetes 将 Web 和应用程序服务器拆分到不同的 Docker 映像是否有性能优势?
- angular - Angular 库、Watch 和 Docker
- python - 需要帮助来了解一种快速排序的实现
- vb.net - 如何通过唯一标识标题或 FF 换页符来解析文本文件?
- c++ - 旋转相机 LookAt 点