如何在where子句的case构造中有条件

时间:2017-08-03 04:51:48

标签: sql oracle

我希望根据表中列的值来设置单独的条件。 我正在尝试这样但不起作用。

SELECT  p.flexible_lunch, b.contract 
FROM   SCH360_ACTIVITY_EMP_BASE p, SCH360_BREAKS_EMP b
WHERE  p.resource_qry_seq = b.resource_qry_seq
AND    p.resource_id = b.resource_id
AND   CASE
        WHEN b.flexible_time IS NULL THEN
            ((b.activity_start >= p.activity_start AND b.activity_end < p.activity_end) OR
            (b.activity_start > p.activity_start  AND b.activity_end <= p.activity_end))
        ELSE
            b.late_start >= p.late_start
        END

错误说'缺少右括号'

这是错的吗? 我们在这种情况下有条件吗? 请纠正我。

3 个答案:

答案 0 :(得分:1)

您可以使用简单的union来处理您的两个案例。

SELECT  p.flexible_lunch, 
        b.contract 
FROM   SCH360_ACTIVITY_EMP_BASE p
inner join SCH360_BREAKS_EMP b  on      p.resource_qry_seq = b.resource_qry_seq
                                AND     p.resource_id = b.resource_id
                                and (   (   b.activity_start >= p.activity_start 
                                        AND b.activity_end < p.activity_end
                                        ) 
                                    OR  (   b.activity_start > p.activity_start  
                                        AND b.activity_end <= p.activity_end
                                        )
                                    )
where b.flexible_time IS NULL

union all 

SELECT  p.flexible_lunch, 
        b.contract 
FROM    SCH360_ACTIVITY_EMP_BASE p
inner join SCH360_BREAKS_EMP b  on      p.resource_qry_seq = b.resource_qry_seq
                                AND     p.resource_id = b.resource_id
                                and     b.late_start >= p.late_start
where   b.flexible_time IS NOT NULL

答案 1 :(得分:1)

不要使用联合,而是试试这个:

SELECT  p.flexible_lunch ,
        b.contract
FROM    SCH360_ACTIVITY_EMP_BASE p
        INNER JOIN SCH360_BREAKS_EMP b ON p.resource_qry_seq = b.resource_qry_seq
                                          AND p.resource_id = b.resource_id
WHERE   ( ( b.flexible_time IS NULL )
          AND ( ( b.activity_start >= p.activity_start
                  AND b.activity_end < p.activity_end
                )
                OR ( b.activity_start > p.activity_start
                     AND b.activity_end <= p.activity_end
                   )
              )
        )
        OR ( ( b.late_start >= p.late_start )
             AND ( b.flexible_time IS NOT NULL )
           )

答案 2 :(得分:1)

你可以通过玩AND / OR条件来无条件地做到这一点。此查询将产生您想要实现的相同输出

SELECT p.flexible_lunch, b.contract
FROM SCH360_ACTIVITY_EMP_BASE p, SCH360_BREAKS_EMP b
WHERE     p.resource_qry_seq = b.resource_qry_seq
AND p.resource_id = b.resource_id
AND ((b.flexible_time IS NULL
        AND (( b.activity_start >= p.activity_start
        AND b.activity_end < p.activity_end)
    OR (b.activity_start > p.activity_start
        AND b.activity_end <= p.activity_end)))
OR b.late_start >= p.late_start)