选择具有特殊FK的最小值,最大值和一行

时间:2014-10-27 17:10:19

标签: oracle select oracle-apex

抱歉,我想不出一个更好的头衔。

我有一张这样的表:

...
DATE (datetime)
PROJECT (number - this is a FK to projects table)
FROM (datetime)
TO (datetime)
...

我需要选择每天的最低FROM值(作为工作日开始的时间),最大TO值(作为工作日结束的时间)以及标记为“BREAK”的项目的FROM和TO “,所以输出看起来像这样:

date     from to     break from break to time spent 
1.1.2011 9:00 17:00 12:00       13:00    7.0

这在某种选择中是否有可能做到?到目前为止,我有这个:

SELECT 
  MIN("FROM_X") AS "FROM",
  MAX("TO_X") AS "TO",
  (MAX("TO_X") - MIN("FROM_X"))*24 AS TIME_SPENT,
  "DAY"
FROM ATTENDANCE_HOURS
GROUP BY DAY

它负责工作日的开始和结束,但我不知道如何包含休息的东西。

1 个答案:

答案 0 :(得分:2)

如果"打破"项目每天只出现一次,你可以使用:

SELECT 
  MIN("FROM_X") AS "FROM",
  MAX("TO_X") AS "TO",
  max(case when project = 'break' then from_x else null end) as "BREAK FROM",
  max(case when project = 'break' then to_x else null end) as "BREAK TO",
  (MAX("TO_X") - MIN("FROM_X"))*24 AS TIME_SPENT,
  "DAY"
FROM ATTENDANCE_HOURS
GROUP BY DAY

如果没有,则需要选择合适的聚合函数。此外,您可以使用此解决方案排除您的"休息"前两列的项目:

SELECT 
  max(case when project <> 'break' then from_x else null end) as "FROM",
  max(case when project <> 'break' then to_x else null end) as "TO",