如何根据另一个表组摘要获取摘要?

时间:2015-01-08 02:28:07

标签: sql oracle oracle11g

业务规则:仅当trans_code分组的总数(trans_amount)>时,才获取客户的总cust_points数。 0.

对于客户#1,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 */

1 个答案:

答案 0 :(得分:1)

这是使用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