2017-02-23 80 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字段 –

相關問題