过滤联接查询中的行

时间:2014-07-01 13:35:14

标签: sql oracle join

我无法过滤查询的结果。这是我正在执行的查询:

SELECT 
ORE.ID AS OR_ID, 
ORE.INIT_VERSION AS OR_INIT_VERSION,
ORE.INSERT_DATE AS OR_INSERT_DATE, 
ORE.INIT_DATE AS OR_INIT_DATE,
ORE.END_DATE AS OR_END_DATE, 
ORE.STATE AS OR_STATE,
ORE.ACTION_NAME AS OR_ACTION_NAME,
ORH.STATE_ID AS ORH_STATE_ID,
ORH.INSERT_DATE AS ORH_INSERT_DATE,
CS.STATE AS CS_STATE

FROM ORDER_REQUEST ORE 
INNER JOIN ORDER_REQUEST_HISTORY ORH ON ORH.ORDER_REQUEST_ID = ORE.ID AND ORH.COMPONENT_ID = ORE.ARCH_ID
INNER JOIN COMPONENT_STATE CS ON CS.ID = ORH.STATE_ID
WHERE ORE.ARCH_ID = 219934
AND CS.STATE IN ('CREAZIONE', 'ANNULLATO', 'REVISIONE PIANIFICATA', 'APPROVAZIONE PIANIFICATA', 'APPROVAZIONE RIFIUTATA', 'COMPLETATO', 'COMPLETATA')

返回以下结果:

OR_ID   OR_STATE    OR_INIT_DATE    OR_ACTION_NAME  ORH_STATE_ID    OR_END_DATE     CS_STATE    ORH_INSERT_DATE     OR_INSERT_DATE          OR_INIT_VERSION
8821    COMPLETATA  2014-04-07      ATT             111             2014-06-03      COMPLETATA  15-05-2014 12:48:32 07-04-2014 16:49:42     1
12266   ACQUISITO   2014-06-03      VAR             10018           NULL            CREAZIONE   30-06-2014 18:59:40 03-06-2014 15:53:51     2
12266   ACQUISITO   2014-06-03      VAR             10018           NULL            CREAZIONE   01-07-2014 12:56:20 03-06-2014 15:53:51     2

我想以这样的方式过滤:对于每个OR_ID,我只得到具有最大ORH_INSERT_DATE的行,即结果的第一行和第三行。 我尝试了不同的方法,但似乎都没有。 特别是我试图使JOIN复杂化:

    INNER JOIN ORDER_REQUEST_HISTORY ORH ON ORH.ORDER_REQUEST_ID = ORE.ID AND ORH.COMPONENT_ID = ORE.ARCH_ID AND ORH.INSERT_DATE = (SELECT INSERT_DATE FROM ORDER_REQUEST_HISTORY ORH2 WHERE ORH2.ORDER_REQUEST_ID = ORE.ID)

但它只返回上面结果的第一行。我也尝试以同样的方式使WHERE子句复杂化,但它仍然只返回上面结果集的第一行。

是否有人知道要添加的正确条款是什么?或者我应该通过后续查询并解决好问题?

提前多多感谢,

詹卢卡

1 个答案:

答案 0 :(得分:1)

您可以使用WITH子句和ROW_NUMBER函数执行此操作,如下所示:

WITH CTE AS
(
 SELECT 
 ORE.ID AS OR_ID, 
 ORE.INIT_VERSION AS OR_INIT_VERSION,
 ORE.INSERT_DATE AS OR_INSERT_DATE, 
 ORE.INIT_DATE AS OR_INIT_DATE,
 ORE.END_DATE AS OR_END_DATE, 
 ORE.STATE AS OR_STATE,
 ORE.ACTION_NAME AS OR_ACTION_NAME,
 ORH.STATE_ID AS ORH_STATE_ID,
 ORH.INSERT_DATE AS ORH_INSERT_DATE,
 CS.STATE AS CS_STATE,
 ROW_NUMBER() OVER (PARTITION BY ORE.ID ORDER BY ORH.INSERT_DATE DESC) AS RN
 FROM ORDER_REQUEST ORE 
 INNER JOIN ORDER_REQUEST_HISTORY ORH ON ORH.ORDER_REQUEST_ID = ORE.ID AND      ORH.COMPONENT_ID = ORE.ARCH_ID
 INNER JOIN COMPONENT_STATE CS ON CS.ID = ORH.STATE_ID
 WHERE ORE.ARCH_ID = 219934
 AND CS.STATE IN ('CREAZIONE', 'ANNULLATO', 'REVISIONE PIANIFICATA', 'APPROVAZIONE PIANIFICATA', 'APPROVAZIONE RIFIUTATA', 'COMPLETATO', 'COMPLETATA')
)

SELECT *
FROM CTE
WHERE RN = 1

我们的想法是根据OR_ID进行分区,并找到ORH_INSERT_DATE的最大值行。您也可以通过将*替换为所需的列来仅选择特定列。