Skip to content Skip to sidebar Skip to footer

Where Do I Put A WHERE Statement?

I have the following two tables of data: +----------+------+--------+--+---------------+-------+------------+--+--------+--------+-----------------------------+ | stat_atp | |

Solution 1:

Join the tables and use a correlated subquery for the output:

SELECT t.id_t, t.id_ti, t.Date, 
    (
      select round(100 * sum(ss.fs_1) / sum(ss.fsof_1), 0) 
      from tbltourns_atp as tt inner join stat_atp as ss on tt.id_t = ss.id_t
      where tt.id_ti = t.id_ti and tt.date <= t.date
    ) as output
FROM  tbltourns_atp as t;

Results:

id_t    id_ti   Date        output
1       1       1/1/2019    50
2       1       5/1/2019    31
3       1       3/1/2019    32
4       2       4/1/2019    30
5       2       5/1/2019    30
6       2       6/1/2019    29
7       3       1/1/2019    50
8       3       8/1/2019    33
9       3       2/1/2019    32
10      3       6/1/2019    35

Note that the Output you posted as expected fro id_t 8 and 10 are wrong.


Solution 2:

You could also solve this using joins in place of a correlated subquery, which may offer some improvement in performance:

select t1.id_t, sum(t3.fs_1)/sum(t3.fsof_1) as output
from
    (
        tbltourns_atp t1 inner join tbltourns_atp t2 on
        t1.id_ti = t2.id_ti and t1.date >= t2.date
    ) 
    inner join stat_atp t3 on t2.id_t = t3.id_t
group by t1.id_t

Post a Comment for "Where Do I Put A WHERE Statement?"