2017-04-12 29 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

感谢您的帮助! –