在 case when 语句中使用计算列结果

Use calculated column result in case when statement

我正在使用 Oracle SQL Developer,我有一个声明

select 
c.name as "Customer Name"
cy.country as "Country",
c.startdateutc as "UTC Start Date"
case when c.startdateutc >= To_date('2023-03-12 08:00', 'YYYY-MM-DD hh24:mi') and c.startdateutc <= To_date('2023-11-05 07:00', 'YYYY-MM-DD hh24:mi') then c.startdateutc  - 5/24
else c.startdateutc - 6/24 END AS "New Start Date"
from
customer c
left join country cy
on cy.id = c.countryid
where c.startdateutc >= date '2020-07-01' 

我想根据类似于此的 Case When Column 创建另一个列

case when New Start Date >= To_date('2023-03-12 08:00', 'YYYY-MM-DD hh24:mi') and New Start Date <= To_date('2023-11-05 07:00', 'YYYY-MM-DD hh24:mi') then New Start Date  - 5/24
else New Start Date - 6/24 END AS "New Calc Start Date"

提前致谢

一个选项是嵌套 CASEs:

select 
  case when 
            case when     c.startdateutc >= To_date('2023-03-12 08:00', 'YYYY-MM-DD hh24:mi') 
                      and c.startdateutc <= To_date('2023-11-05 07:00', 'YYYY-MM-DD hh24:mi') 
                 then c.startdateutc  - 5/24
                 else c.startdateutc - 6/24 
            END 
       then something
  else something_else
end new_case_column
from ...

另一种是将当前查询用作子查询(或 CTE),例如

with current_query as
  (select 
   c.name as "Customer Name"
   cy.country as "Country",
   c.startdateutc as "UTC Start Date"
   case when c.startdateutc >= To_date('2023-03-12 08:00', 'YYYY-MM-DD hh24:mi') and    
             c.startdateutc <= To_date('2023-11-05 07:00', 'YYYY-MM-DD hh24:mi') then 
             c.startdateutc  - 5/24
        else c.startdateutc - 6/24 
   END AS new_start_date
   from
   customer c
   left join country cy
   on cy.id = c.countryid
   where c.startdateutc >= date '2020-07-01' 
)
select case when new_start_date = something then something
            else something else
       end
from current_query join ...

考虑像这样使用子查询:

SELECT COLUMNNAMES
FROM (
    SELECT COLUMNNAMES
    FROM TABLEname2
    WHERE condition
    ) t

在这种情况下:

SELECT 
    t.*
    ,CASE 
        WHEN New_Start_Date >= To_date('2023-03-12 08:00', 'YYYY-MM-DD hh24:mi')
            AND New_Start_Date <= To_date('2023-11-05 07:00', 'YYYY-MM-DD hh24:mi')
            THEN New_Start_Date - 5 / 24
        ELSE New_Start_Date - 6 / 24
        END AS "New Calc Start Date"
FROM (
    SELECT c.name AS "Customer Name"
        ,cy.country AS "Country"
        ,c.startdateutc AS "UTC Start Date" 
        ,CASE 
            WHEN c.startdateutc >= To_date('2023-03-12 08:00', 'YYYY-MM-DD hh24:mi')
                AND c.startdateutc <= To_date('2023-11-05 07:00', 'YYYY-MM-DD hh24:mi')
                THEN c.startdateutc - 5 / 24
            ELSE c.startdateutc - 6 / 24
            END AS "New_Start_Date"
    FROM customer c
    LEFT JOIN country cy ON cy.id = c.countryid
    WHERE c.startdateutc >= DATE '2020-07-01'
    ) t