How to remove NULL from case when and then output Oracle SQL Developer

448 views Asked by At

Oracle SQL Developer noob here. I am trying to create a quarterly sales analysis based on warehouse names and output the Quarterly sales as Q1, Q2 etc. Using Drill down query concepts.

I am unsure if what I am doing is in any way related to a Drill Down concept but this is one of my many attempts. I am hoping for a way to remove the null value outputs to be left with proper data.

It is in the hopes that with the removal of the null data, all the outputs related to specific warehouse names will also all output to 1 line. Leaving me with Warehouse_Name(1), Q1 Data, Q2 Data, etc

I am currently using two tables for this query which are Warehouse: Warehouse_id, warehouse_name and quantity_sold Time_Period: Date_id, Full_date, Days, Month_short and year.

My Code is as follows:

SELECT TO_CHAR(Full_date, 'Q') AS MY_QTR, 
    Sum(Quantity_sold) AS HOW_MANY_SOLD_PER_QTR
FROM warehouse, Time_Period 
GROUP BY TO_CHAR(Full_date, 'Q')
ORDER BY 1;
Select warehouse_Name,
case 
when TO_CHAR(Full_date, 'Q') = 1
then Sum(Quantity_sold) 
End as Q1_2019,
case 
when TO_CHAR(Full_date, 'Q') = 2
then Sum(Quantity_sold)
End as Q2_2019,
case 
when TO_CHAR(Full_date, 'Q') = 3
then Sum(Quantity_sold)
End as Q3_2019,
case 
when TO_CHAR(Full_date, 'Q') = 4
then Sum(Quantity_sold)
End as Q4_2019
FROM warehouse w1, Time_Period t1
where Q1_2019 IS NOT NULL
GROUP BY warehouse_Name,TO_CHAR(Full_date, 'Q')
ORDER BY 1;

Which provides me with an output of

Waarehouse_Name   Q1   Q2   Q3   Q4
--------------- ---- ---- ---- ----
Henderson        990 Null Null Null    
Henderson       Null 1001 Null Null
Henderson       Null Null 1012 Null
Henderson       Null Null Null 1012
1

There are 1 answers

8
Aman Singh Rajpoot On

Edit :

As mentioned by @mathguy

“He was using conditional SUM (conditional by quarter) and also was grouping by quarter in the GROUP BY clause. If you remove the quarter from GROUP BY (which you eventually did), there would be no more null in the output already. The main point of the answer has noting to do with adding else 0 to the case expressions. “

So using else here is unnecessary Removing quarter from GROUP BY does the thing.

Select warehouse_Name,  SUM( case when TO_CHAR(Full_date, 'Q') = 1 then Quantity_sold else 0 End) as Q1_2019,
                        SUM( case when TO_CHAR(Full_date, 'Q') = 2 then Quantity_sold else 0 End) as Q2_2019,
                        SUM( case when TO_CHAR(Full_date, 'Q') = 3 then Quantity_sold else 0 End) as Q3_2019,
                        SUM( case when TO_CHAR(Full_date, 'Q') = 4 then Quantity_sold else 0 End) as Q4_2019
FROM warehouse w1
where Full_date IS NOT NULL
GROUP BY warehouse_Name
ORDER BY 1;