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

时间:2018-05-22 06:22:34

标签: oracle join aggregate-functions min

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的联接记录,并选择具有最早时间戳的记录。

无论如何,如果我不能在JOIN条件下重复相同的WHERECREATION_TIMESTAMP条款?

2 个答案:

答案 0 :(得分:2)

有几种方法可以获得最早的记录,并避免两次输入相同的标准。

使用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);

使用窗口功能

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。)

答案 1 :(得分:0)

您可以使用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;