使用SQL Server Management Studio
假设我有一个事务表,其中包含User, Date, Transaction amount。我想要一个查询,当达到一定数量时返回日期-比如100。
例如,同一个用户执行10笔交易,花费10欧元。我希望查询选择最后一次交易的日期,因为那是他的交易量达到100的时候。当然,一旦达到100,查询就不应该再更改最近事务的日期,而应该将其保留为达到100的日期。
在pgadmin上写的,但我认为语法应该是一样的。
with cumulative as
(
select customer_id,
sum(amount) over (partition by customer_id order by payment_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) cum_amt,
payment_date
from payment
)
select customer_id
, min(payment_date) as threshold_reached
from cumulative
where cum_amt>=100
group by customer_id
case when sum(amt) over (partition by user order by date) - amt < 100
and sum(amt) over (partition by user order by date) >= 100
then 1 else 0 end