在同一个表中添加引用的值

时间:2017-11-22 04:05:01

标签: sql oracle

以下是我正在使用的数据:

表:客户

   ID FIRST_NAME LAST_NAME  CATEGORY  SPONSORID BALANCE_DUE
 10001 Rita       Rush       MEMBER                     8.25
 10002 Becky      Finch      MEMBER                     3.75
 10003 Joyce      Wilson     FRIEND        10002          20
 10004 Carol      Crane      FRIEND        10002          10
 10005 Tricia     Tatum      MEMBER
 10006 Lucy       Nash       MEMBER                     1.75
 10007 Larry      Bell       FRIEND        10001
 10008 Ron        Welsh      FRIEND        10009

我想要一个显示MEMBER及其余额总和+ FRIEND余额的查询的一些指导/有用提示。请记住,SPONSORID引用了ID。

它应该最终看到这些方面:

    ID FIRST_NAME LAST_NAME  BALANCE_DUE
 10001 Rita       Rush              8.25
 10002 Becky      Finch            33.75
 10006 Lucy       Nash              1.75

提前致谢!

2 个答案:

答案 0 :(得分:0)

尝试一下:

SELECT CUSTOMERS.ID member_id, (CUSTOMERS.BALANCE_DUE + sponsor_sums.balance_sum) total_balance_due
FROM CUSTOMERS,
(SELECT SPONSORID, SUM(BALANCE_DUE) balance_sum
FROM CUSTOMERS
WHERE CATEGORY = 'FRIEND'
GROUP BY SPONSORID) AS 'sponsor_sums'
WHERE CUSTOMERS.CATEGORY = 'MEMBER'
AND CUSTOMERS.ID = sponsor_sums.SPONSORID;

答案 1 :(得分:0)

您可以使用2 cte(公用表格式)从表格中提取memberFRIEND汇总记录,并加入2 cte's以获得所需的结果,如下所示。

with cte1 as 
(select * from table1
 where CATEGORY = 'MEMBER'
 ),
 cte2 as
 (select SPONSORID, sum(BALANCE_DUE) as BALANCE_DUE 
  from table1
  where CATEGORY = 'FRIEND'
  group by SPONSORID
  )

select t1.Id, 
       t1.First_Name, 
       t1.Last_Name, 
       t1.BALANCE_DUE + coalesce(t2.BALANCE_DUE,0)  as BALANCE_DUE
from cte1 t1
left join cte2 t2
on t1.id = t2.SponsorId
order by t1.Id;

OR 派生表格如下:

SELECT
  t1.id,
  t1.FIRST_NAME,
  t1.LAST_NAME,
  t1.BALANCE_DUE + COALESCE(t2.BALANCE_DUE, 0) AS BALANCE_DUE
FROM (SELECT *
      FROM table1
      WHERE CATEGORY = 'MEMBER') t1
LEFT JOIN (SELECT SPONSORID, BALANCE_DUE
           FROM table1
           WHERE CATEGORY = 'FRIEND'
           GROUP BY SPONSORID) t2
ON t1.id = t2.SponsorId
ORDER BY t1.Id

<强>结果:

+-------+------------+-----------+-------------+
|  ID   | FIRST_NAME | LAST_NAME | BALANCE_DUE |
+-------+------------+-----------+-------------+
| 10001 | Rita       | Rush      | 8.25        |
| 10002 | Becky      | Finch     | 33.75       |
| 10005 | Tricia     | Tatum     | NULL        |
| 10006 | Lucy       | Nash      | 1.75        |
+-------+------------+-----------+-------------+

<强> DEMO