查询表并与另一行进行比较

时间:2014-01-17 15:37:45

标签: sql oracle

我有一个名为CLOCK的表,它有列ID:

 NUMBER, TIME_IN: DATE, TIME_OUT: DATE, START_LUNCH: VARCHAR2, and STOP_LUNCH: VARCHAR2.

我想选择其中TIME_IN和TIME_OUT为NOT NULL且START_LUNCH ='Y'并且STOP_LUNCH为NULL并且该ID没有CLOCK_IN不为NULL且CLOCK_OUT为空的行。

除了最后一部分,我想确保没有另一行具有相同的id,其中CLOCK_IN不是NULL且CLOCK_OUT为NULL,我可以得到它。任何帮助表示赞赏。

SELECT ID FROM CLOCK
WHERE TIME_IN IS NOT NULL
AND TIME_OUT IS NOT NULL
AND START_LUNCH = '50'
AND START_LUNCH IS NULL

2 个答案:

答案 0 :(得分:2)

您可以使用not existsnot in。以下是使用not in的示例:

SELECT ID FROM CLOCK
WHERE TIME_IN IS NOT NULL
AND TIME_OUT IS NOT NULL
AND START_LUNCH = '50'
AND START_LUNCH IS NULL
AND ID NOT IN (SELECT ID
               FROM CLOCK
               WHERE CLOCK_IN IS NOT NULL
               AND CLOCK_OUT IS NULL)

子查询选择与您要排除的条件匹配的所有ID,not in负责实际排除它们。

答案 1 :(得分:0)

使用不存在:

SELECT a.id
  FROM clock a
 WHERE a.time_in IS NOT NULL
   AND a.time_out IS NOT NULL
   AND a.start_lunch = '50'
   AND a.start_lunch IS NULL
   AND NOT EXISTS (SELECT 'X'
                     FROM clock b
                    WHERE b.clock_in IS NOT NULL
                      AND b.clock_out IS NULL
                      AND b.id = a.id);