oracle 修改SQL查询以包含条件作为时间戳之间差异的一部分

hts6caw3  于 2023-05-06  发布在  Oracle
关注(0)|答案(2)|浏览(222)

我有一个查询如下的作品:-

select a.account_id AS ACCOUNT_ID, a.customer__id AS CUS_ID, b.first_Name AS NAME,
b.last_time - a.last_time AS LAST_TIME_DIFFERENCE
from tableA a, tableB b
where a.account_id = b.account_id AND a.customer__id = b.customer__id
AND EXTRACT(HOUR FROM (a.last_time - b.last_time)) > 6
ORDER BY b.first_name

last_time是timestamp类型的列。我希望添加一个if/else,这样如果(a.last_time - b.last_time)之间的天数差为0,只有这样我才必须将EXTRACT(HOUR FROM(a.last_time - b.last_time))〉6条件添加到“AND”子句(作为WHERE的一部分)。如何修改此查询以包含该逻辑?

ruyhziif

ruyhziif1#

您可以用途:

SELECT a.account_id,
       a.customer__id AS CUS_ID,
       b.first_Name AS NAME,
       b.last_time - a.last_time AS LAST_TIME_DIFFERENCE
FROM   tableA a
       INNER JOIN tableB b
       ON     a.account_id   = b.account_id
          AND a.customer__id = b.customer__id
          AND a.last_time    > b.last_time + INTERVAL '6' HOUR
ORDER BY b.first_name

(无论last_time列是日期还是时间戳,它都有效。)
或者,如果last_time列是时间戳:

FROM   tableA a
       INNER JOIN tableB b
       ON     a.account_id   = b.account_id
          AND a.customer__id = b.customer__id
          AND a.last_time - b.last_time > INTERVAL '6' HOUR

或者,如果last_time列是DATE s(在Oracle中,它始终具有时间分量):

FROM   tableA a
       INNER JOIN tableB b
       ON     a.account_id   = b.account_id
          AND a.customer__id = b.customer__id
          AND a.last_time - b.last_time > 6/24

或者,您可以确保DATE差值被计算为一个区间,使用:

FROM   tableA a
       INNER JOIN tableB b
       ON     a.account_id   = b.account_id
          AND a.customer__id = b.customer__id
          AND (a.last_time - b.last_time) DAY TO SECOND > INTERVAL '6' HOUR

更新:

如果您希望时间戳在同一天,则:

SELECT a.account_id,
       a.customer__id AS CUS_ID,
       b.first_Name AS NAME,
       b.last_time - a.last_time AS LAST_TIME_DIFFERENCE
FROM   tableA a
       INNER JOIN tableB b
       ON     a.account_id   = b.account_id
          AND a.customer__id = b.customer__id
          AND a.last_time    > b.last_time + INTERVAL '6' HOUR
          AND a.last_time    < TRUNC(b.last_time) + INTERVAL '1' DAY
ORDER BY b.first_name

或:

FROM   tableA a
       INNER JOIN tableB b
       ON     a.account_id   = b.account_id
          AND a.customer__id = b.customer__id
          AND a.last_time - b.last_time > 6/24
          AND a.last_time < TRUNC(b.last_time) + 1
ycl3bljg

ycl3bljg2#

这是一种技巧,你可以利用使用decode操作。

select a.account_id AS ACCOUNT_ID, a.customer__id AS CUS_ID, b.first_Name AS NAME,
 b.last_time - a.last_time AS LAST_TIME_DIFFERENCE 
from tableA a, tableB b 
where 
  a.account_id = b.account_id 
  AND a.customer__id = b.customer__id 
  AND decode(floor(abs(a.last_time - b.last_time)),0,abs(a.last_time - b.last_time)*24,2) > decode(floor(abs(a.last_time - b.last_time)),0,6,1)
ORDER BY b.first_name

相关问题