如何找到丢失的行?

时间:2015-10-06 06:19:13

标签: sql oracle

我有一张如图所示的表格。 table structure

专栏onCreate(...)每年应该有1到12个月。多年来,我们错过了几个月的数据加载。我需要一个查询,它将获取没有所有12个月的年份以及缺少的月份数。

请帮忙。

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

试试这样:

将其发布到空的查询窗口并根据您的需要进行调整。

MyData包含一个&#34;完整&#34; 2013年,9月在2014年失踪,6月和9月在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

答案 2 :(得分: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

答案 3 :(得分:0)

select * 
from (select count (-1) total, year from rag_month_dim group by year) as table
where total < 12.

你有一年没有12个月的数据和你的数据总月记录。