代码之家  ›  专栏  ›  技术社区  ›  user2102665

使用聚合函数根据最小时间戳筛选记录

  •  0
  • user2102665  · 技术社区  · 7 年前
    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_DETAILS ABC_CUSTOMERS 然后选择时间戳最早的一个。

    不管怎样,如果我不能重复同样的话 JOIN WHERE 条款 CREATION_TIMESTAMP 条件?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Thorsten Kettner    7 年前

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

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

        2
  •  0
  •   Kaushik Nayak    7 年前

    你可以利用 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;