使用下表。我正在尝试获取Party_ID。 我将只有NEW_ORG_ID和ORIGINAL_ID。
使用NEW_ORG_ID,我想获得具有MAX(USR_CRTE_TS)的PARTY_ID。除非,ORIGINAL_ID也要匹配。然后,我希望NEW_ORG_ID和ORIGINAL_ID匹配的PARTY_ID。
PARTY_ID |DIRS_ID |SUPPLIER_ID|ORIGINAL_ID|TRIANGLE_ID|NEW_ORG_ID|USR_CRTE_TS |
------------------|---------|-----------|-----------|-----------|----------|-------------------|
5385606962 |476800490|5385606962 |NULL |NULL |69214683 |2018-09-27 04:56:13|
69214683 |476800490|NULL |2740793553 |NULL |69214683 |2018-09-27 04:54:15|
我尝试了以下方法。请记住,仅在此示例中,我对NEW_ORG_ID和ORIGINAL_ID进行了硬编码。在实际示例中,查询的另一部分提供了NEW_ORG_ID和ORIGINAL_ID。
SELECT DISTINCT PARTY_ID
FROM UNIQUE_IDS UNQ
WHERE
(
CASE
WHEN (
SELECT ts.PARTY_ID
FROM UNIQUE_IDS ts
WHERE (ts.NEW_ORG_ID = '69214683' AND ts.ORIGINAL_ID = '2740793553')
) IS NOT NULL
THEN
(
SELECT ts.PARTY_ID
FROM UNIQUE_IDS ts
WHERE (ts.NEW_ORG_ID = '69214683' AND ts.ORIGINAL_ID = '2740793553')
)
ELSE
(
SELECT ts.PARTY_ID
FROM UNIQUE_IDS ts
WHERE ts.NEW_ORG_ID = '69214683'
AND ts.USR_CRTE_TS = (
SELECT MAX(ts.USR_CRTE_TS)
FROM UNIQUE_IDS ts
WHERE ts.NEW_ORG_ID = '69214683'
)--xref.SBL_GLOB_CSTMR_ID)
)
END
) = UNQ.NEW_ORG_ID
;
答案 0 :(得分:1)
您可以使用ROW_NUMBER()
分析函数来获得标记为1的“最佳”匹配(首先由ORIGINAL_ID
,然后由USR_CRTE_TS
),然后对其进行过滤:< / p>
SELECT PARTY_ID
FROM (
SELECT PARTY_ID,
USR_CRTE_TS,
ROW_NUMBER() OVER (
PARTITION BY PARTY_ID
ORDER BY CASE ORIGINAL_ID
WHEN '2740793553' THEN 0
ELSE 1
END,
USR_CRTE_TS DESC
) RN
FROM UNIQUE_IDS
WHERE NEW_ORG_ID = '69214683'
)
WHERE RN = 1
如果USR_CRTE_TS
可以是NULL
,则在末尾添加另一个条件以符合您的条件:
AND (ORIGINAL_ID = '2740793553' OR USR_CRTE_TS IS NOT NULL)
您可以使用WITH
子句来逐步构建查询。
因此,假设您已经具有选择两个“参数”的工作逻辑,然后将其放在with
子句中,如下所示:
WITH CRIT(SEL_ORG_ID, SEL_ORIGINAL_ID) AS (
SELECT '69214683', '2740793553' FROM DUAL -- this is just an example
)
...,然后像这样继续查询:
), BASE AS (
SELECT UI.PARTY_ID,
UI.USR_CRTE_TS,
UI.ORIGINAL_ID,
CRIT.SEL_ORIGINAL_ID,
ROW_NUMBER() OVER (
PARTITION BY UI.PARTY_ID
ORDER BY CASE UI.ORIGINAL_ID
WHEN CRIT.SEL_ORIGINAL_ID THEN 0
ELSE 1
END,
UI.USR_CRTE_TS DESC
) RN
FROM UNIQUE_IDS UI,
CRIT
WHERE UI.NEW_ORG_ID = CRIT.SEL_NEW_ORG_ID
)
SELECT PARTY_ID
FROM BASE
WHERE RN = 1
AND (ORIGINAL_ID = SEL_ORIGINAL_ID OR USR_CRTE_TS IS NOT NULL)
答案 1 :(得分:0)
我将row_number()
用于条件排序:
select party_id
from (
select party_id,
row_number() over (order by case when original_id = '2740793553' then 1 end,
usr_crte_ts desc) rn
from unique_ids unq
where new_org_id = '69214683')
where rn = 1
如果original_id
匹配,则行具有更高的优先级。第二优先级最高usr_crte_ts
。最后,我们排在第一位。