我在 Oracle 中编写了一个查询,现在需要将其转换为大查询格式,我对大查询非常陌生,需要您的帮助
(to_char(解码(符号(解码(to_char(c.last_updated_time +3, 'D') ,7 , c.last_updated_time +5 ,1 ,c.last_updated_time +5, 2, c.last_updated_time +5,3, c .last_updated_time +4, c.last_updated_time +3) -sysdate),-1,3,1)),' ') 优先级
首先我们使用
last_updated_time
生成一些样本数据。 due_date
是几天后,具体取决于星期几。所以模拟一个周末和工作日。因此,添加到 last_updated_time
是通过 TIMESTAMP_ADD
完成的。由于 Interval
是
根据星期几(从 1 到 7 的数字),使用以下语句:
CASE day_of_the_week WHEN 7 then adding_value ... end
接下来计算
due_date
与今天之间的日期差。 Prio 1 代表过去的due_date
。否则返回Prio 3。
所以我们最终得到这个 BigQuery 查询:
WITH
tbl AS (
SELECT *
from unnest(generate_timestamp_array(timestamp "2024-01-01",timestamp "2024-04-01",interval 1 day ) ) as last_updated_time
)
SELECT *,
IF(
TIMESTAMP_DIFF(TIMESTAMP_ADD( c.last_updated_time, INTERVAL (
CASE EXTRACT(DAYOFWEEK FROM TIMESTAMP_ADD(c.last_updated_time, INTERVAL 3 DAY))
WHEN 7 THEN 5
WHEN 1 THEN 4
WHEN 2 THEN 4
WHEN 3 THEN 4
ELSE 3
END
) DAY ),current_timestamp(), DAY)
>0,3,1) # Prio 1 if day is in past, otherwise Prio 3
||' ' # convert to string with space after
AS Priority,
CASE
WHEN EXTRACT(DAYOFWEEK FROM TIMESTAMP_ADD(c.last_updated_time, INTERVAL 3 DAY)) = 7 THEN
TIMESTAMP_ADD(c.last_updated_time, INTERVAL 5 DAY)
WHEN EXTRACT(DAYOFWEEK FROM TIMESTAMP_ADD(c.last_updated_time, INTERVAL 3 DAY)) IN (1, 2, 3) THEN
TIMESTAMP_ADD(c.last_updated_time, INTERVAL 4 DAY)
ELSE
TIMESTAMP_ADD(c.last_updated_time, INTERVAL 3 DAY)
END
AS due_date
FROM
tbl AS c
order by 1
如您所见,另一种解决方案用于所呈现的
due_date
。之前先完成星期几的案例陈述,然后对每个案例进行日期计算。
我还想评论给定 Oracle 查询的每一步:
-- query with comments above each line
SELECT
-- convert result to string and add a space character
TO_CHAR(
-- The DECODE(x,1,2) function is the (CASE x when 1 then 2 end) structure in BigQuery
DECODE(
-- This SIGN function returns -1 if the value is negative, 0 if zero, and 1 if positive
SIGN(
-- This DECODE function calculates a due date based on the last_updated_time and this date of the week
DECODE(
-- TO_CHAR function converts last_updated_time + 3 days into the day of the week
TO_CHAR(c.last_updated_time + 3, 'D'),
-- If day of the week is Saturday (7), add 5 days
7, c.last_updated_time + 5,
-- If day of the week is Sunday (1), add 5 days
1, c.last_updated_time + 5,
-- If day of the week is Monday (2), add 5 days
2, c.last_updated_time + 5,
-- If day of the week is Tuesday (3), add 4 days
3, c.last_updated_time + 4,
-- For all other days, add 3 days
c.last_updated_time + 3
) - SYSDATE -- Subtracting current system date
),
-- If the result is negative, return prio 3 (due date is today or in the future)
-1, 3,
-- If the result is positive or zero, return prio 1 (due date is in the past)
1
),
' ' -- Convert the result into a character string with a space character
) AS Priority
FROM tbl AS c;