结合加入而不是日期查询

时间:2017-12-25 20:42:49

标签: sql oracle

这是我的2张桌子。 Review_master

id Rev_month Rev_year ...
1  JAN       2017
2  MAR       2017
4  FEB       2017

Review_det

Id Rev_id closed_date (MM/DD/YYYY)
1   1      01/01/2017
2   1      02/01/2017
3   1      01/17/2017
4   2      03/03/2017
5   2      04/03/2017
6   4      02/02/2017
6   4      02/05/2017

现在我需要找出那个月以外关闭的评论数量。审核ID" 1"是一月份,从评论详情表review_detail_id 2在月份关闭,所以应该计算。 最终输出:

Rev_Id #_Closed_outside_month
1       1
2       1
4       0

2 个答案:

答案 0 :(得分:1)

这是一个选项:

SQL> with review_master (id, rev_month, rev_year) as
  2  (select 1, 'jan', '2017' from dual union
  3   select 2, 'mar', '2017' from dual union
  4   select 4, 'feb', '2017' from dual),
  5  review_det (id, rev_id, closed_date) as
  6  (select 1, 1, date '2017-01-01' from dual union
  7   select 2, 1, date '2017-02-01' from dual union
  8   select 3, 1, date '2017-01-17' from dual union
  9   select 4, 2, date '2017-03-03' from dual union
 10   select 5, 2, date '2017-04-03' from dual union
 11   select 6, 4, date '2017-02-02' from dual union
 12   select 7, 4, date '2017-02-05' from dual)
 13  select m.id,
 14    case when to_char(d.closed_date, 'mmyyyy') <>
 15              to_char(to_date(m.rev_month||' '||m.rev_year, 'mon yyyy',
 16                 'nls_date_language = english'), 'mmyyyy')
 17         then 1
 18         else 0
 19    end closed_outside_Month
 20  from review_master m, review_det d
 21  where m.id = d.rev_id
 22    and d.closed_date = (select max(d1.closed_date)
 23                         from review_Det d1
 24                         where d1.rev_id = d.rev_id
 25                        );

        ID CLOSED_OUTSIDE_MONTH
---------- --------------------
         1                    1
         2                    1
         4                    0

SQL>

答案 1 :(得分:1)

有两个要点:

  1. MONclosed date

    rev_month的字面值不平等
     rev_month != to_char(closed_date,'MON')
    
  2. 将两个表与outer join合并。

  3. 因此,您可以轻松使用以下内容:

    select m.id "Rev_id", count(closed_date) "#_Closed_outside_month"
      from Review_det d right outer join Review_master m on ( d.Rev_id = m.id )
        and rev_month != to_char(closed_date,'MON')
     group by m.id
     order by m.id;
    

    D e m o