There are two requests, they are executed from the same database.

select userid, type, sum(amount) from fct_bonus where userid=123 and date<='2016-08-01' group by type CREATE TABLE Tbalance (select userid, sum(case when type = 'IN' then amount when type = 'OUT' then - amount end) as balance from fct_bonus where date <= '2016-08-01' group by userid) SELECT COUNT(userid) AS CountBalance FROM Tbalance WHERE balance > 10000 

It is necessary to start continuous execution for each request separately with changing date. The date list for which you need to perform these queries contains 300 values ​​and is a separate table. That is, each of the two requests must be executed 300 times.

In the assignment, this is called a view / aggregate ...

  • Optimally fast - do not execute queries 300 times, but rewrite as a single query. And even more so - not to create a temporary table, again, all this is easily solved by one request - Mike
  • There are two requests I recalculated several times - well, three requests, not two! And the fact that the third is not numbered does not change anything ... PS. distinct in the first query is superfluous. - Akina
  • But how exactly such a query will look like depends on the database structure and which particular SQL dialect you use. - Mike
  • @Mike create table fct_bonus database structure I use MySql I get acquainted with sql for the first week, so I agree that it was probably easier))) Do not judge strictly))) - Galina Melnikova
  • @Akina thanks, clear distinct!)) - Galina Melnikova

0