在oracle中选择以返回最新的行

时间:2015-10-30 19:49:52

标签: sql database oracle greatest-n-per-group

我有一个票务系统(它),我需要从同一张票的许多其他记录中的表中返回最新记录。

enter image description here

在上面的图片中,您可以看到select的输出(我将在下面粘贴)。 意识到PBTI_WORKORDER_ID列显示了票证ID,我想要做的只是显示最大的request_id(图像上的第一行)。

选择是:

SELECT 
MAX(REQUEST_ID),
(PBTI_WORKORDER_ID),
PBTI_IDREQUISICAO,
TO_CHAR(SECS_TO_DATE(PBTI_DTABERTURA),'DD/MM/YYYY HH24:MI:SS') AS DATA_CRIACAO,
PBTI_GRUPOSUPORTEATUAL                                         AS GRUPO_ATUAL,
TO_CHAR(SECS_TO_DATE(PBTI_DATAENTRADAGRUPO),'DD/MM/YYYY')      AS DATA_ENTRADA,
TO_CHAR(SECS_TO_DATE(PBTI_DATASAIDAGRUPO),'DD/MM/YYYY')        AS DATA_SAIDA_GRUPO,
PBTI_PROXIMOGRUPOSUPORTE                                       AS PROXIMO_GRUPO,
REQUEST_ASSIGNEE,
CATEGORIZATION_TIER_1,
CATEGORIZATION_TIER_2,
CATEGORIZATION_TIER_3,
CUSTOMER_ORGANIZATION,
PBTI_MCU_ORG
FROM PBTI_TABELA_INDICADORES
WHERE PBTI_GRUPOSUPORTEATUAL = 'CENTRAL HD - TRATAMENTO'
GROUP BY (REQUEST_ID),
(PBTI_WORKORDER_ID),
(PBTI_IDREQUISICAO),
(PBTI_DTABERTURA),
(PBTI_GRUPOSUPORTEATUAL),
(PBTI_DATAENTRADAGRUPO),
(PBTI_DATASAIDAGRUPO),
(PBTI_PROXIMOGRUPOSUPORTE),
(REQUEST_ASSIGNEE),
(CATEGORIZATION_TIER_1),
(CATEGORIZATION_TIER_2),
(CATEGORIZATION_TIER_3),
(CUSTOMER_ORGANIZATION),
(PBTI_MCU_ORG)
ORDER BY PBTI_DATAENTRADAGRUPO DESC;

MAX(用于select子句)应该只带第一行,不是吗?

TKS

1 个答案:

答案 0 :(得分:2)

实现此目的的一种方法是生成一组数据,该数据由每个票证的最大request_ID组成(B)。然后,将所有记录加入到基本集(A)中,从而使用联接仅为每个票证/请求保留相关的“最新”记录。

像这样......

SELECT A.* 
FROM PBTI_TABELA_INDICADORES A
INNER JOIN  (SELECT max(request_ID) Request_Id, PBTI_WorkORder_Id, PBTI_IDREQUISICAO
             FROM PBTI_TABELA_INDICADORES
             GROUP BY PBTI_WorkORder_Id, PBTI_IDREQUISICAO) B
  on A.Request_Id = B.Request_Id
 and A.PBTI_WorkORder_Id = B.PBTI_WorkORder_Id
 and A.PBTI_IDREQUISICAO = B.PBTI_IDREQUISICAO