如何组合来自两个记录的值

时间:2015-04-09 20:36:32

标签: sql oracle

大家好,所以我有以下代码,应该查看事件成本,如果已完全支付,则从交易表中找出并从该显示中显示未付余额。

Select CASESTUDY_CLIENT.CLEINT_FNAME as First_Name,  
       casestudy_client.client_sname as Surname, 
       casestudy_client.client_Phonenumber as Phone_number, 
       casestudy_event.event_totalcost- casestudy_transaction.transaction_value as Unpaid_balance
  from casestudy_client
  inner join casestudy_event
    on casestudy_client.client_id = casestudy_event.event_clientid
  inner join casestudy_transaction
    on casestudy_event.event_id = casestudy_transaction.transaction_eventid
  where casestudy_event.EVENT_EVENTSTAGE ='complete' and 
        casestudy_event.event_totalcost > casestudy_transaction.transaction_value;

这很好用但是如果我们有一个多部分事务,那么它就无法获取匹配的事件id并假定它的另一个事件。

在我的测试数据中,我有一个成本为500英镑的事件,一个值为400的事务和一个值为99的事务。当前输出显示两个记录,其中未付余额为100,另一个401.我想展示的只是99

如果可以通过相对简单的方式实现这一点,请告诉我,因为我无法弄清楚如何使其正常工作

2 个答案:

答案 0 :(得分:0)

您需要将交易加在一起。

Select CASESTUDY_CLIENT.CLEINT_FNAME as First_Name,  
       casestudy_client.client_sname as Surname, 
       casestudy_client.client_Phonenumber as Phone_number, 
       casestudy_event.event_totalcost- sum(casestudy_transaction.transaction_value) as Unpaid_balance
  from casestudy_client
  inner join casestudy_event
    on casestudy_client.client_id = casestudy_event.event_clientid
  inner join casestudy_transaction
    on casestudy_event.event_id = casestudy_transaction.transaction_eventid
  where casestudy_event.EVENT_EVENTSTAGE ='complete' and 
        casestudy_event.event_totalcost > casestudy_transaction.transaction_value
GROUP BY CASESTUDY_CLIENT.CLEINT_FNAME, casestudy_client.client_sname, casestudy_client.client_Phonenumber, casestudy_event.event_totalcost

另外,CLEINT_FNAME可能是一个错字。

答案 1 :(得分:0)

您似乎希望在从成本中减去交易价值之前对其进行求和。

Select      CASESTUDY_CLIENT.CLEINT_FNAME as First_Name,
            casestudy_client.client_sname as Surname,
            casestudy_client.client_Phonenumber as Phone_number,
            casestudy_event.event_totalcost- casestudy_transaction.transaction_value as Unpaid_balance
from        casestudy_client
inner join  casestudy_event
    on      casestudy_client.client_id = casestudy_event.event_clientid
inner join  (
    select      casestudy_transaction.transaction_eventid, sum(transaction_value) as transaction_value
    from        casestudy_transaction
    group by    casestudy_transaction.transaction_eventid
    ) as casestudy_transaction
    on      casestudy_event.event_id = casestudy_transaction.transaction_eventid
where       casestudy_event.EVENT_EVENTSTAGE ='complete'
    and     casestudy_event.event_totalcost> casestudy_transaction.transaction_value ;

我可能会离开加入交易子查询,因此您可以包含尚未支付的事件,但这只取决于查询的目标。