Postgresql select until certain total amount is reached

后端 未结 3 1125
没有蜡笔的小新
没有蜡笔的小新 2020-12-10 05:21

I was wondering if I could get any help with the following problem.

I have a table of transactions (simplified below) and I only want to select transactions until my

相关标签:
3条回答
  • 2020-12-10 05:49
    select id, 
           date, 
           amount, 
           running_total
    from (
        select id,
               date,
               amount,
               sum(amount) over (order by date asc) as running_total
        from transactions
    ) t
    where running_total <= 6
    
    0 讨论(0)
  • 2020-12-10 06:08
    select T1.*
    from Transactions as T1
    where 6 - (select sum(T2.amount) 
                   from Transactions as T2 where  T2.id <= T1.id
              ) >= 0
    order by id asc
    

    This query works on SQL Server if Postgres supports subqueries like SQL Server does it can help you

    0 讨论(0)
  • 2020-12-10 06:10

    Although it may not be the most efficent way (as you're still, in essence, selecting everything first), I'd look at using a running total.

    Something like:

    SELECT
      *
    FROM
      (
      SELECT
        id
        , date
        , amount
        , (SELECT SUM(amount) FROM Transactions WHERE id <= t.id) AS RunningTotal
      FROM
        Transactions t
    ) t1
    WHERE
      t1.RunningTotal < 6
    
    0 讨论(0)
提交回复
热议问题