Question

I haven´t done any T-SQL before and were wondering how could I change the script below to differentiate between positive and negative values. At the moment it seems to just to add the two together and giving out wrong values.

I would like to add an IF clause that s.summa would follow rules: e.g

-1 + -1 = -2

1 + -1 = 0

1 + 1 = 2

If I am correct now it is being dealt with "etumerkki", so that if etumerkki variable is 0 s.sum is converted to negative and if etumerkki variable has not been set it remains normal.

SET @stmt = CONCAT( 'INSERT INTO tbl_1 (rivi,rivi_id,isanta_rivi,taso,lihavointi,tili_rivi,otsikko,selite,summa)
                        SELECT  t.rivi , t.rivi_id , t.isanta_rivi , t.taso , t.lihavointi , t.rivi_tyyppi , t.otsikko , t.selite , 
                                CASE etumerkki
                                    WHEN 0 THEN -1 * IFNULL(SUM(s.summa),0.00) 
                                    ELSE IFNULL(SUM(s.summa),0.00) 
                                END AS summa
                        FROM tase_mem t
                                LEFT JOIN kuutio_paakirja s ON s.tili = t.tili
                        WHERE   ' , nyk_summa_ehto , ' 
                                AND s.kpaikka_id = ' , kpaikka_id , ' AND s.projekti_id = ' , projekti_id , ' ' , isanta_ehto , '
                        GROUP BY t.rivi , t.rivi_id , t.taso , t.lihavointi , t.rivi_tyyppi , t.etumerkki , t.otsikko , t.selite;');
    PREPARE stmt FROM @stmt;
    EXECUTE stmt;

Thanks in advance

Était-ce utile?

La solution

Not sure if i follow...

SUM()

does indeed evaluate signed numbers correctly. Eg sum(1, -1) = 0, sum(-1, -1)=-2 and sum(1,1) = 2 See:

select sum(a)
from (
          select 1 as a
union all select -1 
) i

select sum(a)
from (
          select -1 as a
union all select -1 
) i

select sum(a)
from (
          select 1 as a
union all select 1 
) i

However, in your query, you write IFNULL(SUM(s.summa),0.00): This means that your query first sums all s.summa, and AFTER that evaluates IFNULL.

I suppose you want to evalue whether s.summa is null before you add them together. changing the query to SUM(IFNULL(s.summa),0.00) should give you the proper result.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top