--
-- ### Aggregation with case cond
--

drop if exists table t1;
create table t1 ( a string(10), b int, c int, d decimal(10,2), t string(1));
 
insert into t1 values ( 'A', 120, 299, (decimal)30.34, 'C');
insert into t1 values ( 'A', 130, 329, (decimal)13.39, 'C');
insert into t1 values ( 'A', 200, 87, (decimal)7.12, 'C');
insert into t1 values ( 'B', 120, 8, (decimal)0.24, 'C');
insert into t1 values ( 'B', 170, 1, (decimal)2.61, 'C');
insert into t1 values ( 'C', 450, 5, (decimal)99.13, 'D');
insert into t1 values ( 'C', 11, 55, (decimal)78.13, 'D');
insert into t1 values ( 'C', 78, 78, (decimal)98.13, 'D');
insert into t1 values ( 'C', 93, 123, (decimal)111.23, 'D');



select
        sum(b) as sb,
        case when sum(c) < 1000 
                then sum(c)
		else 42 end as th1,
        case when sum(c) < 500 
                then sum(c)
		else 42 end as th2,
        case when sum(d) < (decimal)500.00 
                then sum(d)
		else (decimal)0.00 end as th3,
        case when sum(d) < (decimal)100.00 
                then sum(d)
		else (decimal)0.00 end as th4
from t1;

select
	a,
        sum(b) as sb,
	sum(c) as sc,
        case when sum(c) != 0 
                then ( sum(b) + sum(b) ) / sum(c)
		else 42 end as xy
from t1  group by a;

select
        sum(b) as sb,
	sum(c) as sc,
        case when sum(c) != 0 
                then sum(b) / ( sum(c) + sum(c) )
		else 42 end as xy
from t1 where t = 'X';

select
	a,
        sum(b) as sb,
	sum(c) as sc,
        case when sum(b) != 42 and sum(c) != 0 
                then sum(b) / sum(c)
		else 42 end as xy
from t1  group by a;

