我在下面有查询,
SELECT CASE
WHEN floor(months_between(CAL_DATE, BIRTH_DATE) / 12) BETWEEN 0
AND 20
THEN '1'
WHEN floor(months_between(CAL_DATE, BIRTH_DATE) / 12) BETWEEN 21
AND 30
THEN '2'
WHEN floor(months_between(CAL_DATE, BIRTH_DATE) / 12) BETWEEN 31
AND 40
THEN '3'
WHEN floor(months_between(CAL_DATE, BIRTH_DATE) / 12) BETWEEN 41
AND 50
THEN '4'
ELSE '5'
END ) Age_Band
FROM dual
有没有办法为表达式floor(months_between(CAL_DATE, BIRTH_DATE) / 12)
提供别名,并在下面的case语句中使用它。
CASE floor(months_between(CAL_DATE, BIRTH_DATE) / 12) **age**
WHEN **age** BETWEEN 0 AND 20 THEN '1'
答案 0 :(得分:0)
你不能为CASE语句添加别名,但是,为了使事情更具可读性和紧凑性,我使用子查询进行计算。
#AAA
答案 1 :(得分:0)
您可以使用CTE或子查询。这是一个CTE,因为其他人有一个子查询:
WITH floor AS
(
SELECT floor(months_between(CAL_DATE, BIRTH_DATE) / 12) AS floor
FROM dual
)
SELECT CASE
WHEN f.floor BETWEEN 0 AND 20 THEN '1'
WHEN f.floor BETWEEN 21 AND 30 THEN '2'
WHEN f.floor BETWEEN 31 AND 40 THEN '3'
WHEN f.floor BETWEEN 41 AND 50 THEN '4'
ELSE '5' END AS Age_Band
FROM floor f
答案 2 :(得分:-1)
仅当您使用子查询时:
SELECT CASE
WHEN z.flor BETWEEN 0 AND 20 THEN '1'
WHEN z.flor BETWEEN 21 AND 30 THEN '2'
WHEN z.flor BETWEEN 31 AND 40 THEN '3'
WHEN z.flor BETWEEN 41 AND 50 THEN '4'
else '5' end Age_Band
FROM (SELECT floor(months_between
(CAL_DATE, BIRTH_DATE) / 12) flor
From dual)z
但你也可以这样做:
Select case when months_between(CAL_DATE, BIRTH_DATE) > 60 then 5
else 1 + floor(months_between(CAL_DATE, BIRTH_DATE) / 240) end
From dual
不会做同样的事情吗?