【问题标题】:Get rid of blank result from reg_ex_split_table output从 reg_ex_split_table 输出中删除空白结果
【发布时间】:2021-03-29 09:37:24
【问题描述】:

我有一个查询,它计算一列中的所有单词,并给出单词的频率和频率等级作为结果。出于某种原因,我不断得到一个没有字的行。我该如何摆脱它?

表:

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

【问题讨论】:

  • 您能否提供一个最低限度的可重现示例,以便调查问题?另外,鉴于您要提出一个新问题,我建议您在 your previous question 上接受答案。
  • 抱歉,我已更新问题以包含可重现的示例

标签: sql postgresql count greatest-n-per-group lateral-join


【解决方案1】:

问题在于内部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)

Demo on DB Fiddle

【讨论】:

    【解决方案2】:

    你可以在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
    

    【讨论】:

    • 我试过了,但不幸的是,我仍然得到相同的结果
    猜你喜欢
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    • 2019-02-04
    相关资源
    最近更新 更多