我有一个SQL查询,在该查询中,我希望从表中检索时间戳记录。
但是,如果今天的日期=该记录中的时间戳,则查询只能返回没有时区的时间。
如果记录的时间戳::日期不等于今天的日期,那么返回时间戳。示例:
2013-08-07 18:00:18.692+01
2013-08-09 20:13:09.927+01预期结果:
18:00:18.692
2013-08-09 20:13:09.927+01从这两个时间戳中,我希望能够从今天的日期只检索第一天的时间,但同时从第二个日期检索日期和时间,因为这不是今天的日期。
发布于 2013-08-07 16:39:44
这本质上是一个格式化问题,所以最好在应用程序代码中处理它。但您可以在SQL中完成。
create table t (
ts timestamp not null
);
insert into t values
('2013-01-01 08:00');
insert into t values
(current_timestamp);时间戳数据类型与您希望返回它们的方式不兼容,因此转换为文本是有意义的。
select case when ts::date = current_date then ts::time::text
else ts::text
end
from t;
TS
--
2013-01-01 08:00:00
16:34:52.339发布于 2013-08-07 14:34:10
哪个数据库?
日期总是与日期部分一起存储的,因此这似乎是一个格式问题。下面我有一个解决方案,但实际格式可能有点差。问题似乎是关于逻辑的,您可以很容易地研究格式化字符串以得到您想要的。
这里有一个Oracle解决方案:(请注意,我创建了一个内联视图,其中包含一个,以模拟您的数据。把你的桌子放在那儿就行了。)
select dt, when,
case
when trunc(sysdate) = trunc(dt) then to_char(dt, 'hh24:mi:ss')
else to_char(dt, 'yyyy-dd-mm hh24:mi:ss')
end yourResult
from
(
select sysdate dt, 'today' when
from dual
union
select sysdate-1 dt, 'yesterday' when
from dual
);这里有一个Server解决方案:(同样,还有一个内联视图来模拟您的数据)
select dt, whn,
case
when cast(getDate() As Date) = cast(dt As Date) then convert(varchar(20), dt, 108)
else convert(varchar(20), dt, 120 )
end your_Result
from
(
select getDate() dt, 'today' whn
union
select getDate()-1 dt, 'yesterday' whn
) x;https://stackoverflow.com/questions/18105427
复制相似问题