2015-01-08 49 views
0

业务规则:获取客户仅当总(trans_amount)用于trans_code分组> 0如何根据另一个表组摘要获取摘要?

对于顾客#1总cust_points,汇总在date_code水平(代码10)> 0,因此cust_points总= 70.

为客户#2只码20个总计> 0,总共只有75总cust_points

这里是我的查询:

with customers as 
(select '1' as cust_id, 10 as date_code, 30 as cust_points from dual union all 
    select '1' as cust_id, 10 as date_code, 40 as cust_points from dual union all 
    select '1' as cust_id, 20 as date_code, 22 as cust_points from dual union all --These points should not total because trans_amount sum for code 20 is less than 0 
    select '1' as cust_id, 40 as date_code, 33 as cust_points from dual union all -- These points should not total because there is not trans_amounts > 0 for date_code 
    select '2' as cust_id, 10 as date_code, 20 as cust_points from dual union all 
    select '2' as cust_id, 20 as date_code, 65 as cust_points from dual union all 
    select '2' as cust_id, 20 as date_code, 10 as cust_points from dual 
), 
transactions_row as 
(
select '1' as cust_id, '10' as trans_code, 10.00 as trans_amount from dual union all 
select '1' as cust_id, '20' as trans_code, -15.00 as trans_amount from dual union all 
select '1' as cust_id, '20' as trans_code, -20.00 as trans_amount from dual union all 
select '1' as cust_id, '20' as trans_code, -10.00 as trans_amount from dual union all 
select '1' as cust_id, '30' as trans_code, 30.00 as trans_amount from dual union all 
select '1' as cust_id, '20' as trans_code, -20.00 as trans_amount from dual union all 
select '2' as cust_id, '10' as trans_code, -50.00 as trans_amount from dual union all 
select '2' as cust_id, '20' as trans_code, 20.00 as trans_amount from dual 
) 
select cust_id, 
     sum(cust_points) 
from customers 
where cust_id in 
( 
select cust_id 
     from (
select cust_id, trans_code, sum(trans_amount) 
from transactions_row 
group by cust_id, trans_code 
having sum(trans_amount) > 0 
) 
) 
group by cust_id 



Desired Results 

CUST_ID CUST_POINTS 
    1   70 /* (30 because total trans_amount for tran_code(10) > 0 + 
        40 because total trans_amount for tran_code(10) > 0) */ 

    2  75 /* Do not include the 20 points because total trans_amt for 10 < 0 */ 
+0

不宜客户2为75点(65 + 10)? – sgeddes

+0

是的,应该是75 ..我会进行编辑。 – zundarz

+0

另一个问题是,您是否必须使用CTE或者仅仅是表格的例子?它可能会影响解决方案。 – sgeddes

回答

1

她E公司采用exists一个办法:

select cust_id, 
     sum(cust_points) 
from customers c 
where exists (
    select 1 
    from transactions_row tr 
    where tr.trans_code = c.date_code 
     and tr.cust_id = c.cust_id 
    group by tr.trans_code, tr.cust_id 
    having sum(tr.trans_amount) > 0 
) 
group by cust_id