首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >with运算符返回空行时的PostgreSQL情况

with运算符返回空行时的PostgreSQL情况
EN

Stack Overflow用户
提问于 2019-06-10 01:16:18
回答 3查看 53关注 0票数 0

我正在尝试根据当前日期生成支付期间值。当我运行下面的查询时,它返回了正确的支付期间,但我得到了额外的空行。怎样才能去掉空行?

代码语言:javascript
复制
select  distinct case  when current_date >= to_date(begin_payperiod_date, 'mm/dd/yy') 
    and current_date < to_date(end_payperiod_date, 'mm/dd/yy') 
    then cast(regexp_replace(itc_pp, '[^0-9]*', '', 'g') as integer)-1  end AS current_pp
from    actacc.payperiod_conversion_all_years

当前它返回:

代码语言:javascript
复制
1 null
2 18

我只想返回第二行。

EN

回答 3

Stack Overflow用户

发布于 2019-06-10 01:19:33

case逻辑移动到where子句:

代码语言:javascript
复制
select (cast(regexp_replace(itc_pp, '[^0-9]*', '', 'g') as integer)-1) AS current_pp
from actacc.payperiod_conversion_all_years
where current_date >= to_date(begin_payperiod_date, 'mm/dd/yy') and
      current_date < to_date(end_payperiod_date, 'mm/dd/yy') ;

我取下了select distinct。您没有数据样本,因此不清楚是否有必要这样做。如果是,您可以将其重新添加进来。

请注意,您应该使用适当的日期/时间数据类型来存储日期,而不是以字符串的形式。如果您这样做了,那么转换步骤就不必要了。

票数 0
EN

Stack Overflow用户

发布于 2019-06-10 01:20:01

您应该使用where条件来筛选行:

代码语言:javascript
复制
select  distinct cast(regexp_replace(itc_pp, '[^0-9]+', '', 'g') as integer)-1 AS current_pp
from    actacc.payperiod_conversion_all_years
where current_date >= to_date(begin_payperiod_date, 'mm/dd/yy') 
  and current_date < to_date(end_payperiod_date, 'mm/dd/yy')

此外,仅仅通过匹配空字符串来再次将其替换为空字符串是没有意义的,因此我在您的正则表达式中将*更改为+

票数 0
EN

Stack Overflow用户

发布于 2019-06-10 01:38:24

在您的查询中,您仅定义了记录的大小写属于-

代码语言:javascript
复制
current_date >= to_date(begin_payperiod_date, 'mm/dd/yy')
AND current_date < to_date(end_payperiod_date, 'mm/dd/yy')

因此,超出该日期范围的所有记录都将返回NULL,因为您没有定义任何内容,如果该日期超出该范围怎么办。您可以为该日期范围之外的记录定义ELSE部分。脚本可以如下所示-

代码语言:javascript
复制
SELECT 
DISTINCT 
       CASE
           WHEN current_date >= to_date(begin_payperiod_date, 'mm/dd/yy')
                AND current_date < to_date(end_payperiod_date, 'mm/dd/yy') 
                THEN CAST(regexp_replace(itc_pp, '[^0-9]*', '', 'g') AS INTEGER) - 1
            ELSE itc_pp 
            -- Here you can keep the original value or do some 
            -- adjustment as per requirement to keep sync in values data type. 
       END AS current_pp
FROM actacc.payperiod_conversion_all_years; 

如果您在where子句中添加日期过滤条件,则脚本应如下所示:

代码语言:javascript
复制
SELECT 
DISTINCT CAST(regexp_replace(itc_pp, '[^0-9]*', '', 'g') AS INTEGER) - 1 current_pp       
FROM actacc.payperiod_conversion_all_years
WHERE current_date >= to_date(begin_payperiod_date, 'mm/dd/yy')
AND current_date < to_date(end_payperiod_date, 'mm/dd/yy'); 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56516761

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档