2

我有一个 SQL 查询,我想从表中检索时间戳记录。

但是,如果今天的日期 = 该记录中的时间戳,则查询必须只返回没有时区的时间。

如果记录的 timestamp::date 不等于今天的日期,则返回时间戳。例子:

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

从这两个时间戳中,我希望能够从第一个开始检索时间,因为它是今天的日期,但从第二个开始检索日期和时间,因为它不是今天的日期

4

2 回答 2

0

哪个数据库?

日期始终与日期部分一起存储,因此这似乎是一个格式问题。我在下面有一个解决方案,但实际格式可能有点偏差。问题似乎与逻辑有关,您可以轻松地研究格式化字符串以获得所需的内容。

这是一个 Oracle 解决方案:(请注意,我使用来自 DUAL 的 UNION 创建了一个内联视图来模拟您的数据。只需在此处添加您的表。)

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
);

这是一个 SQL 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;
于 2013-08-07T14:34:10.937 回答
0

这本质上是一个格式问题,因此最好在应用程序代码中处理它。但是你可以在 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-07T16:39:44.603 回答