limiting the rows to where the sum a column equals a certain value in MySQL

前端 未结 8 2028
闹比i
闹比i 2020-11-29 08:32

I want to write a query which returns all rows until the sum of one of the columns value reaches a certain value.

For example in the table below:

           


        
相关标签:
8条回答
  • 2020-11-29 09:27

    As no DBMS is given, the following is an ANSI SQL solution which works on a wide range of DBMS:

    select *
    from (
        select date_column, 
               etc, 
               sum(Meeting) over (order by date_column asc) run_sum
        from meetings
    ) t
    where run_sum <= 7
    order by date_column asc;
    

    (I used the column name date_column instead of date because DATE is a reserved word in SQL and should not be used as a column name to avoid problems)

    0 讨论(0)
  • 2020-11-29 09:30

    Here's a way which should work in MySQL :

    SELECT
      O.Id,
      O.Type,
      O.MyAmountCol,
      (SELECT
         sum(MyAmountCol) FROM Table1
       WHERE Id <= O.Id) 'RunningTotal'
    FROM Table1 O
    HAVING RunningTotal <= 7
    

    It involves calculating a running total and selecting records while the running total is less than or equal to the given number, in this case 7.

    SQL Fiddle

    0 讨论(0)
提交回复
热议问题