oracle 筛选列间隔年到月

ukqbszuj  于 2022-11-03  发布在  Oracle
关注(0)|答案(1)|浏览(169)

我有一列,它看起来像https://i.stack.imgur.com/j7Nwh.png,格式是+Year-Month,我需要提取一些信息,例如:

  • 如果期限为0,则返回“无保修”
  • 如果期间大于0,则返回number年number月...

我知道我必须使用一些Case或IF Else结构

kwvwclae

kwvwclae1#

使用CASE表达式:

SELECT warranty_period,
       CASE warranty_period
       WHEN INTERVAL '0-0' YEAR TO MONTH
       THEN 'No warranty'
       ELSE TO_CHAR(warranty_period)
       END AS descr
FROM   table_name

其中,对于示例数据:

CREATE TABLE table_name (warranty_period) AS
SELECT INTERVAL '0-0' YEAR TO MONTH FROM DUAL UNION ALL
SELECT INTERVAL '0-1' YEAR TO MONTH FROM DUAL UNION ALL
SELECT INTERVAL '1-0' YEAR TO MONTH FROM DUAL UNION ALL
SELECT INTERVAL '1-2' YEAR TO MONTH FROM DUAL;

输出:
| 保修期|描述|
| - -|- -|
| +00-00|无保修|
| +00-01| +00-01|
| +01-00| +01-00|
| +1 -2| +1 -2|
或者,如果您想要不同的格式,则EXTRACT组件部分:

SELECT warranty_period,
       CASE warranty_period
       WHEN INTERVAL '0-0' YEAR TO MONTH
       THEN 'No warranty'
       ELSE EXTRACT(YEAR FROM warranty_period) || 'y ' || EXTRACT(MONTH FROM warranty_period) || 'm'
       END AS descr
FROM   table_name

输出:
| 保修期|描述|
| - -|- -|
| +00-00|无保修|
| +00-01| 0年1个月|
| +01-00| 1年0月|
| +1 -2| 1年2个月|
或:

SELECT warranty_period,
       CASE 
       WHEN warranty_period <= INTERVAL '0-0' YEAR TO MONTH
       THEN 'No warranty'
       WHEN warranty_period < INTERVAL '1-0' YEAR TO MONTH
       THEN EXTRACT(MONTH FROM warranty_period) || ' months'
       WHEN EXTRACT(MONTH FROM warranty_period) = 0
       THEN EXTRACT(YEAR FROM warranty_period) || ' years'
       ELSE EXTRACT(YEAR FROM warranty_period) || ' years and ' || EXTRACT(MONTH FROM warranty_period) || ' months'
       END AS descr
FROM   table_name

输出:
| 保修期|描述|
| - -|- -|
| +00-00|无保修|
| +00-01| 1个月|
| +01-00| 1年|
| +1 -2| 1年零2个月|
fiddle

相关问题