[英]Conditional Substitute in Select PostgreSQL
My table has end_date
column as Date
type我的表有end_date
列作为Date
类型
It will have an actual value, a default value or NULL value它将有一个实际值、一个默认值或 NULL 值
2000-01-01
in yyyy-MM-dd format which is populated on 1st of every month默认日期为2000-01-01
,采用 yyyy-MM-dd 格式,在每月 1 日填充I need to make a query which will return the difference in days if it has an actual end date or blank if NULL or default value is there.如果 NULL 或默认值存在,我需要进行查询,如果它有一个实际的结束日期或空白,它将返回天数的差异。
Select GREATEST(0, DATE_PART('day', end_date::timestamp - CURRENT_DATE))
This is the best bet I could manage as of now.这是我目前能做的最好的赌注。 Any way of doing it without If-Else
conditions?没有If-Else
条件的任何方式?
Try to use this in your select-list:尝试在您的选择列表中使用它:
NULLIF(end_date, '2000-01-01') - CURRENT_DATE
The NULLIF
if will return NULL
, iff both parameters are the same, and the first parameter otherwise.如果两个参数相同, NULLIF
if 将返回NULL
,否则返回第一个参数。 Subtraction with a NULL
value (on any side of the operator) will yield NULL
as well, thus this will give you a "blank" output if end_date
is not set or is set to the default (if you desire some other special value, surround this "query" with a COALESCE
and add your default-blank-value as its second parameter).用NULL
值(在运算符的任何一侧)进行减法也会产生NULL
,因此这将为您提供“空白” end_date
值,如果您不希望设置其他值,则设置默认值这个“查询”与COALESCE
并添加您的默认空白值作为其第二个参数)。 Otherwise you get your desired difference.否则你会得到你想要的差异。
I do not see, why there should be any need to cast to TIMESTAMP
.我不明白,为什么需要强制转换为TIMESTAMP
。 This will make the subtration to return an INTERVAL
, but you want an INTEGER
and this is what you get by subtracting two DATE
s.这将使减法返回一个INTERVAL
,但您需要一个INTEGER
,这就是您减去两个DATE
得到的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.