Search code examples
sqlsumsubquerywindow-functions

SQL SUM until condition


I have a table itineraire that have 4 colums, order, id_arret, nom, temp_moyen .

enter image description here

so i want to SUM the temp_moyen until the id_arret = X and stops

exemple:

if id_arret=5 the SUM sould be : 0+5+4+3+6= 18


Solution

  • You can use a where clause to filter the values you want:

    select sum(temp_moyen)
    from t
    where id_arret < ?;
    

    If you wanted a different column for the stops, say nom, then you can use a subquery:

    select sum(temp_moyen)
    from t
    where t.order < (select t2.order from t t2 where t2.id_arret = ?);