2015-10-06 54 views
-1

我有一張如圖所示的表格。 table structure如何找到缺失的行?

MONTH_NO應該每年有1到12個月。幾年來,我們錯過了幾個月的數據加載。我需要一個查詢,它可以獲取那些沒有全部12個月的年份以及缺失的月份數。

請幫忙。

+1

對於誰投反對票,請解釋爲什麼海報不能改善問題/從中吸取教訓。 –

+0

我沒有downvote,但解釋可能是:1)圖片中的測試數據使得難以闡述解決方案,2)沒有「這是我所嘗試」部分。 – Shnugo

+0

請發佈創建和插入語句。並顯示您的預期輸出。參見[如何提出一個好問題](http://tkyte.blogspot.in/2005/06/how-to-ask-questions.html)。 –

回答

0

試試這樣說:

後該到一個空查詢窗口和適應您的需求。

邁德特包含一個 「滿」 2013年,九月中缺少2014年六月和九月是缺少在2015年

DECLARE @OneToTwelve TABLE(Nmbr INT) 
INSERT INTO @OneToTwelve VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12); 

DECLARE @myData TABLE(yearNo INT, MonthNo INT) 
INSERT INTO @myData VALUES 
(2013,1),(2013,2),(2013,3),(2013,4),(2013,5),(2013,6),(2013,7),(2013,8),(2013,9),(2013,10),(2013,11),(2013,12) 
,(2014,1),(2014,2),(2014,3),(2014,4),(2014,5),(2014,6),(2014,7),(2014,8),(2014,10),(2014,11),(2014,12) 
,(2015,1),(2015,2),(2015,3),(2015,4),(2015,5),(2015,7),(2015,8),(2015,10),(2015,11),(2015,12); 

WITH AllYears AS 
(
    SELECT DISTINCT yearNo FROM @myData 
) 
,AllCombinations AS 
(
    SELECT * 
    FROM @OneToTwelve AS months 
    CROSS JOIN AllYears 
) 
SELECT * 
FROM AllCombinations 
LEFT JOIN @myData AS md ON AllCombinations.Nmbr =md.MonthNo AND AllCombinations.yearNo=md.yearNo 
WHERE md.MonthNo IS NULL 
+1

OP在Oracle上不是SQL Server。 –

+0

@LalitKumarB,哦,是的... Thx的提示...也許答案有助於闡述一種方法......魔術字是「理貨表」。 – Shnugo

+0

在Oracle中,您只需使用**分析函數** MAX()OVER()'。 –

1

例如 -

with mth 
    as (select level as month_no 
      from dual 
     connect by level <= 12), 
    yrs as (select distinct year from rag_month_dim) 
select m.year, m.month_no 
    from (select year, month_no 
      from yrs, mth) m, 
     rag_month_dim r 
where m.year = r.year(+) 
    and m.month_no = r.month_no(+) 
group by m.year, m.month_no 
having max(r.month_no) is null 
order by year, month_no 
0
select distinct year, m.lev 
    from rag_month_dim a 
    join 
    (
    select level lev 
    from dual 
    connect by level <= 12 
) m 
    on 1=1 
    minus 
    select year, month_no 
    from rag_month_dim 
    order by 1, 2 
0
select * 
from (select count (-1) total, year from rag_month_dim group by year) as table 
where total < 12. 

你有一年的數據中沒有12個月的數據和總的月份記錄。