0

我有两个表 PROCESS 和 STEP 以及里面的一些数据,如下所示。(他们有 1-N 的关系。)

PROCESS ->

ID START_TIME STARTED_BY STATUS
1  31/08/2012 User1      FINISHED
2  31/08/2012 User2      FINISHED
3  05/09/2012 User3      ACTIVE

STEP ->

ID PROCESS_ID START_TIME END_TIME   STATUS
1  1          31/08/2012 02/09/2012 FINISHED  
2  1          02/09/2012 03/09/2012 FINISHED    
3  1          03/09/2012 10/09/2012 FINISHED  
4  2          31/08/2012 04/09/2012 FINISHED  
5  2          04/09/2012 06/09/2012 FINISHED  
6  2          06/09/2012 09/09/2012 FINISHED  
7  3          05/09/2012 06/09/2012 FINISHED    
8  3          06/09/2012 NULL       ACTIVE

我需要的是一个 JOIN,它将为我提供已完成流程的开始和结束时间,如下所示:

PROCESS_ID START_TIME END_TIME  
1          31/08/2012 10/09/2012  
2          31/08/2012 09/09/2012

我需要写什么样的 JOIN 语句来完成这个?

4

2 回答 2

2

为避免拉入PROCESS_ID 3,需要先聚合过滤

HAVING 子句将确保您忽略表中 PROCESS_ID 3 的所有行STEP。一个简单的WHERE END_TIME IS NOT NULLWHERE .. 'FINISHED'不会做的。在 JOIN 之后也不会聚合

SELECT
   P.PROCESS_ID,
   S.StartTime, S.EndTime
FROM
   PROCESS P
   JOIN
   (
   SELECT
      PROCESS_ID,
      MIN(START_TIME) AS StartTime,
      MAX(END_TIME) AS EndTime
   FROM
      STEP
   GROUP BY
      PROCESS_ID
   HAVING
      COUNT(*) = COUNT(END_TIME) -- only where we have no END_TIME nulls
   ) S ON P.PROCESS_ID = S.PROCESS_ID

例如,还有其他带有 NOT EXISTS 的选项可以忽略 ACTIVE 行,但我在这里只使用 END_TIME 和 NULL 来忽略 STEP 行

于 2012-09-13T11:58:50.207 回答
1

看起来您需要 anINNER JOIN并使用MINandMAX函数。

SELECT PROCESS.PROCESS_ID, MIN(START_TIME), MAX(END_TIME)
FROM PROCESS
INNER JOIN STEP ON STEP.PROCESS_ID = PROCESS.PROCESS_ID
GROUP BY PROCESS.PROCESS_ID
于 2012-09-13T11:59:31.977 回答