2017-04-12 30 views
0
date     | raw_date 
NULL     | 01/01/2016 
2016-09-13 13:00:00+00 | 01/02/2016 
2016-09-13 13:00:00+00 | NULL 

有沒有一種方法來創建一個新的臨時場:date_temp W/C採用最新的值,如果它不爲空,並且使用raw_date的值,如果日期爲null,並且使用date_temp領域中的ORDER BY條款。使用上面的例子,結果應該是這樣的:如何通過SQL實時創建臨時字段並在ORDER BY子句中使用該臨時字段?

date_temp 
2016-01-01 12:00:00+00 
2016-09-13 13:00:00+00 
2016-09-13 13:00:00+00 

回答

0

您應該能夠使用COALESCE(date, to_date(raw_date,'MM/DD/YYYY'))

我假設你_raw_date_列是文本/字符串數據類型。您需要首先將其投射到日期才能使用合併。如果您要在該列中獲得一系列格式變體,則需要添加其他邏輯。

REF:(https://www.postgresql.org/docs/8.1/static/functions-conditional.html

+0

感謝。我在查詢中使用了DISTINCT,它引發了這個錯誤:'錯誤:對於SELECT DISTINCT,ORDER BY表達式必須出現在選擇列表中。任何想法我怎麼能使它工作? –

+0

將它添加到您的SELECT語句中。你能分享整個查詢和你想完成什麼嗎? –

+1

'SELECT DISTINCT「event」。* FROM「event」team.id = event.team1_id內部加入球隊或team.id = event.team2_id聯盟內部加入聯賽.id = team.league_id WHERE(league.type ILIKE' (date',raw_date :: date)desc',我將它修改爲:'SELECT DISTINCT COALESCE(date,raw_date ::)'(在'('','','')中的狀態)日期),「事件」。*從「事件」內部團隊team.id = event.team1_id或team.id = event.team2_id內部加盟聯賽在league.id = team.league_id WHERE(league.type ILIKE'pro ')AND(狀態在('0','1','2'))ORDER BY COALESCE(date,raw_date :: date)desc'並且工作 –

1

使用coalesce()to_date()

with my_table(date, raw_date) as (
values 
    (NULL::date, '01/01/2016'), 
    ('2016-09-13 13:00:00+00', '01/02/2016'), 
    ('2016-09-13 13:00:00+00', NULL) 
) 

select coalesce(date, to_date(raw_date, 'DD/MM/YYYY')) as date_temp 
from my_table 
order by 1; 

date_temp 
------------ 
2016-01-01 
2016-09-13 
2016-09-13 
(3 rows) 
+0

感謝您的幫助! –