我有假日表,其中包含以下字段
COLUMN_NAME DATA_TYPE
-------------------------------
HOLIDAY_ID NUMBER(10,0)
HOLIDAY_NAME VARCHAR2(150 BYTE)
HOLIDAY_DATE TIMESTAMP(6)
DAY_OF_WEEK VARCHAR2(20 BYTE)
HOLIDAY_TYPE_ID NUMBER
,样本数据为
HOLIDAY_ID HOLIDAY_NAME HOLIDAY_DATE DAY_OF_WEEK HOLIDAY_TYPE_ID
-------------------------------------------------------------------------------
305 Republic Day 26-01-17 12:00:00.000000000 AM Thursday 1
306 Maha Shivratri 24-02-17 12:00:00.000000000 AM Friday 1
我使用以下查询来获取特定月/年的holiday_date: 的 (QUERY)
select nvl((select to_char(holiday_date,'DD/MM/YY') holiday
from admin_holiday where to_char(holiday_date,'DD-MON-YYYY') like '%-JUN-2016%'
and holiday_type_id=1 and to_char(holiday_date,'Day') not like 'Sun%'
and to_char(holiday_date,'Day') not like 'Sat%'),'0') holiday from dual
如果结果为null(即月份/年= JUN / 2016),则此工作正常但当月份包含多个假期(即月份/年份)时,“单行子查询返回多行”错误= 2016年10月)
如何编写查询,如果查询返回多行,则显示那些结果,否则显示“0”表示NULL结果?
[注意:假期符合印度日历]
答案 0 :(得分:0)
您应该考虑将查询更改为:
SELECT NVL(TO_CHAR(holiday_date,'DD/MM/YY'), '0') holiday
FROM admin_holiday
WHERE TO_CHAR(holiday_date,'MON-YYYY') = 'JUN-2016'
--WHERE TO_CHAR(holiday_date,'yyyymm') = '201606'
AND holiday_type_id = 1
AND TO_CHAR(holiday_date,'Day') NOT IN ('Sun', 'Sat');
答案 1 :(得分:0)
您需要将nvl函数应用于列,结果如下:
select nvl(to_char(holiday_date,'DD/MM/YY'),'0') holiday
from (select 1 as dummy from dual) d left join admin_holiday
on to_char(holiday_date,'DD-MON-YYYY') like '%-JUN-2016%'
and holiday_type_id=1 and to_char(holiday_date,'Day') not like 'Sun%'
and to_char(holiday_date,'Day') not like 'Sat%'
旁注:了解如何撰写sargable queries
答案 2 :(得分:0)
SELECT NVL(TO_CHAR(holiday_date,'DD/MM/YY'), '0') holiday
FROM admin_holiday
WHERE TO_CHAR(holiday_date,'MON-YYYY') = 'JUN-2016'
--WHERE TO_CHAR(holiday_date,'yyyymm') = '201606'
AND holiday_type_id = 1
AND TO_CHAR(holiday_date,'Day') NOT IN ('Sun', 'Sat')
union all
select '0' from dual where not exists(SELECT NVL(TO_CHAR(holiday_date,'DD/MM/YY'), '0') holiday
FROM admin_holiday
WHERE TO_CHAR(holiday_date,'MON-YYYY') = 'JUN-2016'
--WHERE TO_CHAR(holiday_date,'yyyymm') = '201606'
AND holiday_type_id = 1
AND TO_CHAR(holiday_date,'Day') NOT IN ('Sun', 'Sat'))