使用聚合函数根据 MIN 时间戳过滤记录

Using aggregation function to filter record based on MIN timestamp

SELECT * FROM ABC_CUSTOMER_DETAILS abc_detail
INNER JOIN ABC_CUSTOMERS abc_cust
ON abc_detail.ID=abc_cust.CUSTOMER_ID
WHERE abc_detail.COUNTRY_CODE='KE'
AND CREATION_TIMESTAMP=(SELECT MIN (CREATION_TIMESTAMP)
                        FROM ABC_CUSTOMER_DETAILS abc_detail
                        INNER JOIN ABC_CUSTOMERS abc_cust
                        ON abc_detail.ID=abc_cust.CUSTOMER_ID
                        WHERE abc_detail.COUNTRY_CODE='KE');

上面的脚本查询连接记录从 ABC_CUSTOMER_DETAILSABC_CUSTOMERS 和 select 以及具有最早时间戳的记录。

无论如何,如果我不能在 CREATION_TIMESTAMP 条件下重复相同的 JOINWHERE 子句?

您可以使用 MIN() 分析函数。

SELECT
    *
FROM
    (
        SELECT
            abc_detail.*,
            abc_cust.*,
            MIN(creation_timestamp) OVER(
                PARTITION BY abc_detail.id
            ) AS min_timestamp
        FROM
            abc_customer_details abc_detail
            INNER JOIN abc_customers abc_cust
        ON abc_detail.id = abc_cust.customer_id
        WHERE
            abc_detail.country_code = 'KE'
    )
WHERE
    creation_timestamp = min_timestamp;

有多种方法可以获取最早的记录并避免重复输入相同的条件。

使用 FETCH FIRST ROWS(自 Oracle 12c 起可用)

select * 
from abc_customer_details cd
join abc_customers c on c.id = cd.customer_id
where cd.country_code = 'KE'
order by creation_timestamp
fetch first row only;

使用 CTE(WITH 子句)

with cte as
(
  select * 
  from abc_customer_details cd
  join abc_customers c on c.id = cd.customer_id
  where cd.country_code = 'KE'
)
select *
from cte
where (creation_timestamp) = (select min(creation_timestamp) from cte);

使用 window 函数

select *
from
(
  select cd.*, c.*, min(creation_timestamp) over () as min_creation_timestamp
  from abc_customer_details cd
  join abc_customers c on c.id = cd.customer_id
  where cd.country_code = 'KE'
)
where creation_timestamp = min_creation_timestamp;

(顺便说一句,我更改了所有这些查询中的加入条件。你似乎极不可能在 abc_customer_details.id = abc_customers.customer_id 上加入。)