Search code examples
phpmysqlsqlcodeigniter-2

Error on over() Clause for am calculate the rows based on id's to next or previous value in mysql


I am facing an issue where my query is not executing and I am getting the error near the over clause but I want result like see the pic below: enter image description here

I mean I want result like 25000-9000 =16000 ; 16000-5000 =11000; display output like that guys and here is my query

query:
SELECT s.id, s.cust_id, 
s.package_name,s.pending_amount,s.pack_received_amount, s.return_amount, 
s.payment_type,s.total_package_amount, SUM('s.pending_amount') OVER (ORDER 
BY s.id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW AS s.balance FROM 
payment s WHERE s.cust_id = S1307 and s.package_name= switzerland

My error was here screen shot of images guys:


Solution

  • This is your query:

    select . . .,
           sum(s.pending_amount) over (order by s.id) as balance 
    from payment s 
    where s.cust_id = S1307 and s.package_name = 'switzerland';
    

    If you don't have too many rows, a simple subquery will suffice:

    select . . .,
           (select sum(s2.pending_amount)
            from payment s2
            where s2.id <= s.id and
                  s2.cust_id = s.cust_id and
                  s2.package_name = s.package_name
           ) as balance 
    from payment s 
    where s.cust_id = 'S1307' and
          s.package_name = 'switzerland';