问题
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');
Above script query join record from ABC_CUSTOMER_DETAILS
to ABC_CUSTOMERS
nd select thw one with earliest timestamp.
Anyway if I able not to repeat the same JOIN
and WHERE
clause in CREATION_TIMESTAMP
condition?
回答1:
There are several ways to get the earliest record and to avoid having to type the same criteria twice.
Using FETCH FIRST ROWS (available as of 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;
Using a CTE (WITH clause)
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);
Using window functions
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;
(I changed the join criteria in all these queries, by the way. It just does seem extremely unlikely you want to join on abc_customer_details.id = abc_customers.customer_id
.)
回答2:
You could make use of MIN()
analytic function.
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;
来源:https://stackoverflow.com/questions/50461060/using-aggregation-function-to-filter-record-based-on-min-timestamp