Sample table 'table':

|table1----|--table2--|--table3---| |----------|----------|-----------| |User------| 5000-----|-15-02-2016| |admin-----| 3500-----|-18-03-2016| |guest-----| 2000-----|-19-03-2016| |guest2----| 200------|-23-03-2016| |guest3----| 2000-----|-24-03-2016| 

You need to select the date of the first row of the last rows where the sum of the rows on the table2 column is more than 4000. That is, according to the table above at the end should be 19-03-2016

  • What is SQL dialect? On MySQL it is necessary to solve variables, on other DBMS window functions. - Mike
  • And the "last lines" means sorted backwards and folded, take the most recent entry, if we add less the last but one and so on. ? - Mike
  • Microsoft SQL Server - Dowlpack
  • Mike, yes. This is exactly what is needed. - Dowlpack

1 answer 1

 select * from ( select col1, col2, dt, sum(col2) over(order by DT desc) as S from Table ) A where S<500 

In this example, the entries with the cumulative sum of the column col2 less than 500 and are sorted by the DT column in the reverse order. Those. take the latest recording date.

  • Thanks for the help! Exactly what is needed. A little bit corrected by himself and everything turned out - Dowlpack