将两个查询合并为一个 - Oracle

时间:2018-06-07 13:08:51

标签: sql oracle

尝试合并以下两个涉及否定的查询,最后也删除了所需的行。如果使用MINUS单独运行它们,我将获得所需的结果。

 SELECT *
      FROM table1 t1
     WHERE t1.b_c IN ('A', 'B') AND t1.d_id IN ('2', '3')
           AND ( (t1.a_d >= '1-May-2018'AND t1.a_d <= '15-May-2018')
                OR (t1.a_r >= '1-May-2018'  AND t1.a_r <= '15-May-2018'))
           AND (    t1.a_m = 'AC'
                AND t1.s = 'SW'
                AND t1.c_m IN ('DM', 'SW')
                AND t1.d_m IN ('DM', 'SW')
                OR ((t1.a_m = 'NO' AND t1.s = 'SW')
  AND (   (t1.d_m = 'DM' AND t1.c_m = 'DM')
       OR (t1.d_m = 'SW' AND t1.c_m = 'DM')
       OR NOT (t1.d_m = 'DM' AND t1.c_m = 'SW')
       OR (t1.d_m = 'SW' AND t1.c_m = 'SW'))))
           AND ( (t1.a_m,t1.s,t1.d_m,t1.c_m,t1.d_s) NOT IN
  ( ('NO', 'SW', 'SW', 'DM', 'X001'),
   ('NO', 'SW', 'SW', 'DM', 'XXXX')))

    MINUS
    (SELECT *
       FROM table1 t1
      WHERE t1.b_c IN ('A', 'B') AND t1.d_id IN ('2', '3')
            AND ( (t1.a_d >= '1-May-2018' AND t1.a_d <= '15-May-2018')
                 OR (t1.a_r >= '1-May-2018'   AND t1.a_r <= '15-May-2018'))
            AND t1.dept_id IN ('20', '35')
            AND t1.a_m IN ('AC', 'NO')
            AND t1.s = 'SW'
            AND t1.c_m = 'DM'
            AND t1.d_m IN ('DM', 'SW')
            AND ((t1.o_b = 'X001' AND t1.s_s = 'X001' ) OR (t1.o_b = 'XXXX'   AND t1.s_s = 'XXXX'))
            AND REGEXP_LIKE (t1.r_no, '^(20PS|35RE)'))

综合查询:

SELECT *
  FROM table1 t1
 WHERE t1.b_c IN ('A', 'B') AND t1.d_id IN ('2', '3')
       AND ( (t1.a_d >= '1-May-2018' AND t1.a_d <= '15-May-2018')
            OR (t1.a_r >= '1-May-2018' AND t1.a_r <= '15-May-2018'))
       AND t1.a_m IN ('AC', 'NO')
       AND t1.s = 'SW'
       AND t1.c_m IN ('DM', 'SW')
       AND t1.d_m IN ('DM', 'SW')
       AND (NOT ( ( (t1.a_m, t1.s, t1.d_m, t1.c_m, t1.d_s) IN
                       ( ('NO', 'SW', 'SW', 'DM', 'X001'),
                        ('NO', 'SW', 'SW', 'DM', 'XXXX')))
                 OR ( (t1.s, t1.d_m, t1.c_m) IN ( ('SW', 'DM', 'SW')))
                 OR ( ( (t1.a_m, t1.s, t1.d_m, t1.c_m, t1.o_b, t1.b_b, t1.s_s) IN
                           ( ('AC', 'SW', 'DM', 'DM', 'XXXX', 'X001', 'XXXX'),
                            ('AC', 'SW', 'DM', 'DM', 'X001', 'XXXX', 'X001'))
                       AND REGEXP_LIKE (t1.r_no, '^(20PS|35RE)')))))

当我运行合并查询时,删除了所需的行。

t1.a_m t1.s t1.d_m t1.c_m t1.o_b t1.b_b t1.s_s t1.r_no
AC     SW   DM     DM                          35REXXXX

请让我知道我在哪里弄错了。

1 个答案:

答案 0 :(得分:0)

这是一种非常天真的方法,但我认为它对您有用。

nopython=True

我刚刚接受了与原始设置不同的MINUS条件部分,并添加了NOT。

可能有可能进一步改善这一点,但没有进一步的背景,似乎不值得。