I have a Holiday table with following fields
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
and the sample data is
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
I have used the following query to get the holiday_date of a particular month/year: (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
This works fine if the result is null(ie for month/year= JUN/2016) but gives "single-row subquery returns more than one row" error when the month contains more than one holiday (ie for month/year= OCT/2016)
How do I write a query such that if the query returns multiple rows then display those results else display '0' for NULL result?
[ NOTE : The holidays are as per the Indian calendar]
You should consider changing your query to this:
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');
You need to apply the nvl function to the column, to to the result, like this:
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%'
On a side note: learn how to write sargable queries
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'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.