2016-06-10 425 views
1

我想在過去12個月中顯示一些平均值,但是沒有6月/ 7月的數據,所以我想要顯示月份的標題但僅顯示0 3列Oracle - 如果當月沒有數據,則顯示0

目前它只能顯示8至5月這是10行,所以它擺脫公式和圖表等

select to_char(Months.Period,'YYYY/MM') As Period, coalesce(avg(ec.hours_reset),0) as AvgOfHOURSReset, coalesce(AVG(ec.cycles_reset),0) as AvgofCycles_Reset, Coalesce(AVG(ec.days_reset),0) as AvgofDAYS_Reset 
from (select distinct reset_date as Period from engineering_compliance 
where reset_date between '01/JUN/15' and '31/MAY/16') Months 
left outer join engineering_compliance ec on ec.reset_date = months.Period 
WHERE EC.EO = 'AT CHECK' 
group by to_char(Months.Period,'YYYY/MM') 
order by to_char(Months.Period,'YYYY/MM') 

; 
(select distinct to_char(reset_date,'YYYY/MM') as Period from engineering_compliance 
where reset_date between '01/JUN/15' and '31/MAY/16') Months; 

回答

1

查詢是相當不錯的,它的不遠處工作。

您需要替換Months表部分。無論在ec表中是否有任何數據,您每個月只需要一行。

您可能可以合成一些數據,而無需在自己的模式中使用任何實際表格。

例如:

SELECT 
    extract(month from add_months(sysdate,level-1)) Row_Month, 
    extract(year from add_months(sysdate,level-1)) Row_Year, 
    to_char(add_months(sysdate,level-1),'YYYY/MM') Formatted_Date, 
    trunc(add_months(sysdate,level-1),'mon') Join_Date 
FROM dual 
CONNECT BY level <= 12; 

給出:

ROW_MONTH,ROW_YEAR,FORMATTED_DATE,JOIN_DATE 
6,2016,'2016/06',1/06/2016 
7,2016,'2016/07',1/07/2016 
8,2016,'2016/08',1/08/2016 
9,2016,'2016/09',1/09/2016 
10,2016,'2016/10',1/10/2016 
11,2016,'2016/11',1/11/2016 
12,2016,'2016/12',1/12/2016 
1,2017,'2017/01',1/01/2017 
2,2017,'2017/02',1/02/2017 
3,2017,'2017/03',1/03/2017 
4,2017,'2017/04',1/04/2017 
5,2017,'2017/05',1/05/2017 

選項1:內聯編寫的子查詢到你的查詢,在開始一個月和最後一行的數字12代替SYSDATE可改變了你想要的系列的月份數。選擇2(可以在各種情況和查詢中更加方便地使用):使用上面的SQL編寫一個長期系列的視圖(例如,1970年1月至2199年12月)。然後,您可以在join_date的任何開始和結束月份加入該視圖。它會給你每月一行,你可以從其列中選擇格式化的日期。

相關問題