满足条件后计算所有记录和输出值 [SQL]

Count all records and output values once a condition is met [SQL]

我想计算所有客户和return第 3 位客户的注册日期。

基本上评估注册的客户数量,一旦注册的客户数量达到 3 到 return,注册日期和第 3 个客户的 ID

样本table

customer_id     signup_date   
3993            2019-01-01
9392            2019-01-02
2143            2019-01-03
8372            2019-01-04

输出table

customer_id   signup_date
2143          2019-01-03

使用row_number()过滤需要的值:

row_number() → bigint
Returns a unique, sequential number for each row, starting with one, according to the ordering of rows within the window partition.

-- sample data
WITH dataset (customer_id, signup_date ) AS (
    VALUES (3993, date '2019-01-01'),
  (9392, date '2019-01-02'),
  (2143, date '2019-01-03'),
  (8372, date '2019-01-04')
) 

--query
select customer_id, signup_date
from (
    select *, 
        row_number() over(order by signup_date) rn
    from dataset
)
where rn = 3

输出:

customer_id signup_date
2143 2019-01-03

请注意,在匹配日期的情况下(即几行具有相同的日期)return 值未定义,因此您需要应用额外的排序(例如按 id - row_number() over(order by signup_date, customer_id) rn)(或者考虑使用 rankrow_number 的组合来 return 多个结果)

select * from (
  select 
    customer_id, 
    signup_date, 
    rank() over (order by signup_date) 
  from signups
) sub where sub.rank = 3;
 customer_id | signup_date | rank 
-------------+-------------+------
        2143 | 2019-01-03  |    3
(1 row)

你可以使用

select customer_id, signup_date
  from SampleTable
 order by signup_date
offset 2
 fetch next 1 rows

你可以使用这样的东西:

SELECT customer_id, signup_date

FROM (
  SELECT ROW_NUMBER() OVER (ORDER BY signup_date) AS row_num
             , customer_id
             , signup_date
  FROM your_table
) -- AS sub
WHERE row_num = 3

注册日期总是按升序排列吗? 通常,当 table 有大量行时,Rank() 函数会更好用。 Rank() 比 Row_Number() 快。我的建议是仅在需要快速获得结果时才使用子查询。如果查询需要每天使用、重复使用,请尝试使用 CTE 以获得更好的可读性和性能。

With CTE_Customer_Signup_Date AS (

SELECT Rank() OVER (ORDER BY signup_date) AS Rank
             , customer_id
             , signup_date
  FROM your_table

)

Select customer_id, signup_date from CTE_Customer_Signup_Date 
where Rank =3