2017-02-23 75 views
-1

嗨我试图做这个查询当前年份和第一次发布的年份是相同的,但它不起作用。我该怎么做?如何提取“where”区域中的timestamp字段的年份并使用postgres 9.6比较当前年份?

我想选择first_published字段(TimeStamp格式)的年份到当前年份的字段。

select distinct name, userid, code, last_updated, first_published 
from users 
where date_part('year', first_published) = date_part('year', current_date) 
    and first_published is not null 

select distinct name, userid, code, last_updated, first_published 
from users 
where extract(year from first_published) = date_part(year from current_date) 
    and first_published is not null 

错误:

ERROR: function date_part(unknown, character varying) does not exist 
LINE 7: where date_part('year', first_published) = date_part('year',... 
      ^
HINT: No function matches the given name and argument types. You might need to add explicit type casts. 
********** Error ********** 

ERROR: function date_part(unknown, character varying) does not exist 
SQL state: 42883 
Hint: No function matches the given name and argument types. You might need to add explicit type casts. 
Character: 298 

first_published场的图像

The image of first_published field

+2

“*不起作用*”不是有效的Postgres错误消息。你需要告诉我们你期望的是什么,你得到什么,为什么你得到的不是你想要的。 –

+0

为什么标题说postgresql ** 9.6 **和标签说** 9.4 **?哪一个? –

+0

我用您的要求更新了问题@a_horse_with_no_name –

回答

1

right syntaxdate_part数的功能是:

date_part('year', first_published) 

假设first_published是时间戳。

问题可能是该字段的空值。在靠近你有:

where date_part('year', first_published) = date_part('year', current_date) 
    and first_published is not null 

的date_part数函数调用occure 以前is not null评价。当该字段的值为空时,会导致异常。

我想更换其中的接近这样的:

where first_published is not null and 
date_part('year', first_published) = date_part('year', current_date) 

可以解决这个问题。

你也试试:

where date_part('year', coalesce(first_published, current_date +370)) = date_part('year', current_date) 

说明:的​​3210功能日期在明年替换空值和first_published时什么也不做不为空。

+0

的定义“*这会导致一个异常,当值此字段为空*“这是错误的。 'date_part()'或'extract()'可以绝对处理空值,并且在这种情况下将简单地返回null。 –

+0

'first_published不为空'也没用。 –

+0

@a_horse_with_no_name你说得对。道歉,我回答没有测试。 –

0

错误是相当清楚的:

ERROR: function date_part(unknown, character varying) does not exist

参数,first_published,是一个字符串,不是日期 - 尽管你在文本中说了什么,我不认为错误信息会误导。您需要将其转换为日期。

你可以尝试:

where date_part('year', first_published::date) = date_part('year', current_date) 

但是,您可能需要采取的格式考虑。

+0

我实现了这个问题,你可以看到图像,first_published字段 –

相关问题